Canvas content disappering on resize [duplicate] - html

This question already has answers here:
Resize HTML5 canvas element
(3 answers)
Closed 8 years ago.
Probably I'm missing something fundamental.
I'm filling a canvas with objects. On user input I need to resize the canvas (thus scaling the content).
JS (simplified):
var c = document.getElementById('c');
var cc = c.getContext('2d');
cc.beginPath();
cc.rect(20, 20, 20, 12);
cc.fill();
function resizeCanvas(size){
var c = document.getElementById('c');
var cc = c.getContext('2d');
// This will make the content disappear
c.width = c.style.width = c.height = c.style.height = size;
}
HTML
<canvas id="c" width="200" height="200"></canvas>
<br/>
<button onclick='resizeCanvas(100);return false;'>Resize</button>
CSS
canvas {border: 1px solid black}
The canvas is resized but the content is blanked. Any idea?
jsfddle here

By changing either width or height -and obviously by changing both-, you completely redefine the canvas, so in fact it is quite logical that the canvas content is cleared : how should it change ?
Should it scale ? , re-use existing pixels values, but how ? centered, ... ??
That was even a 'trick' at some time : to clear a canvas, just do canvas.width = 0 then canvas.width = oldWidth , and that will clear things up. Since clearRect or fillRect are now faster that this trick, it has no reason to be used any more.
So when your canvas get resized, it will get cleared. It's up to you to decide of the policy you want when such resize occur : will you scale old canvas and copy it on the new one, or copy at same scale centered, or will that be an up/left most copy ??
you decide.
If you have a 'scene graph', meaning : if you are able to redraw every objects of your canvas, there's no real issue.
If you don't, you have to do some efforts to get the old content on the new canvas.
Something like (untested) :
function resizeCanvas(size){
var c = document.getElementById('c');
var canvasCopy = document.createElement('canvas');
canvasCopy.width = c.width; canvasCopy.height = c.height;
canvasCopy.getContext('2d').drawImage(c, 0,0 ); // copy the 'old' canvas
// This will make the content disappear
c.width = c.style.width = c.height = c.style.height = size;
var cc = c.getContext('2d');
cc.drawImage(canvasCopy, 0, 0) ; // or you might scale, or center, or...
}

Related

Pixi.js - Unable to set sprite width to full width of canvas

Ultimately I want to have a canvas that fills the entire viewport width of the browser and have an image on the canvas fill the entire width of that canvas. I'm taking advantage of pixi.js's displacement filter so that I can create a pseudo 3d effect using a depth map underneath it. The code I'm currently using is
let app = new PIXI.Application();
var w = window.innerWidth;
var h = w / ratio;
app.view.style.width = w + 'px';
app.view.style.height = h + 'px';
document.body.appendChild(app.view);
let img = new PIXI.Sprite.from("images/horses.png");
img.width = w;
img.height = h;
app.stage.addChild(img);
depthMap = new PIXI.Sprite.from("images/horses-depth.png");
depthMap.renderable = false;
depthMap.width = img.width;
depthMap.height = img.height;
img.addChild(depthMap);
app.stage.addChild(depthMap);
displacementFilter = new PIXI.filters.DisplacementFilter(depthMap, 0);
app.stage.filters = [displacementFilter];
Here's a screenshot of it in action.
I even tried manually setting the width to the viewport pixel width on the canvas and the sprite to the actual pixel width of the viewport width and it still wasn't the right size. Manually setting the width for the viewport and sprite to the exact same number also doesn't work; the sprite is inexplicably smaller than the canvas.
I tried to look at the documentation of the sprite class and see if there is something unusual about how sprites handle widths but I couldn't find anything https://pixijs.download/dev/docs/PIXI.Sprite.html
How can I create a pixi.js sprite that fills the entire width of the canvas in order to make both the canvas and the sprite fill the entire viewport width?
pixijs.download
PixiJS API Documentation
Documentation for PixiJS library

How to detect that the AlphaMaskFilter is completely gone in easeljs/createjs

I am doing a little scratch/reveal game based on the AlphaMaskFilter example:
http://createjs.com/demos/easeljs/AlphaMaskReveal.html
I want to detect that the the mask is completely gone, or use a threshold (90% scratched for example).
I read the doc on AlphaMaskFilter, shape and graphics objects and im not really sure how to achieve this.
Im not even sure i Have acess to the pixel information and check the alpha channel to detect it, but even so, I wonder if I will performance issue.
any help is welcome, thanks.
**** EDIT **** ADD TO THE ACCEPTED ANSWER ****
So, I was able to have the pct of transparency using the AlphaMapFilter (thanks Lanny).
The AlphaMapFilter offer you a mapping to the alpha channel of all the pixels.
Here is a little sample code that worked for me:
// mShapeToScratch is a createjs Shape. like in the http://createjs.com/demos/easeljs/AlphaMaskReveal.html example
var alphaMaskFilter = new createjs.AlphaMapFilter(mShapeToScratch.cacheCanvas);
var canvas = alphaMaskFilter.alphaMap;
var ctx = canvas.getContext("2d");
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var alphaData = imgData.data;
var pixelTotal = rect.h*rect.w;
var transparentPixel = 0;
// rect.h is the height of the image and rect.w is the width not shown in the example
for (var y = 0; y < rect.h; ++y)
{
for (var x=0; x < rect.w; ++x)
{
var pixelIdx = (y*rect.w + x);
if(alphaData[pixelIdx] > 128) // transparent will be 255.
{
transparentPixel++;
}
}
console.log("transparent % = " + transparentPixel/pixelTotal);
This example checks all the pixels, but it's pretty easy to check one every X pixels to speeds up checks as Lanny suggested.
The alpha mask uses canvas composite operation, and not pixel access, so without some completely custom approach, there isn't a great way to do this.
Iterating pixels (check out AlphaMapFilter as an example) would work - but could be fairly slow. Maybe checking every 4th, 10th, or 25th pixel would speed it up.
Cheers.

Pixels twice its size

I just created little pixel art for my project http://i.imgur.com/9FLj6Uk.png. And I want to use it on my site. As you can see, it's small pixel art. I want one pixel to be drawn as 2*2 pixels instead of 1*1 pixel. I would redraw the picture with using 2*2 pixels instead of one but that seems to be bad solution.
I tried to use CSS on it
img.pixel {
width: 32px;
height: 32px
}
but that doesn't work, it shows weird shades in my browser. I want to see hard pixels. Does anyone know any solution for this problem?
This is the problem when I use the CSS above
Pixel art is tough in browsers, mainly due to lack of universal browser support of "pixelated" or "crisp-edges" image rendering. It should be supported in CSS4.
Currently the CSS stack looks like this, although it looks as if Chrome 30 and Opera 16 have broken support for CSS solutions
image-rendering:optimizeSpeed;
image-rendering:-moz-crisp-edges;
image-rendering:-o-crisp-edges;
image-rendering:optimize-contrast;
image-rendering:-webkit-optimize-contrast;
-ms-interpolation-mode: nearest-neighbor;
See this answer by #Phrogz, with a test case. Also see mozilla's documentation on the subject. For universal support now, a JS solution may have to work for the time being such as seen here on the great article drawing pixels is hard:
var resize = function( img, scale ) {
// Takes an image and a scaling factor and returns the scaled image
// The original image is drawn into an offscreen canvas of the same size
// and copied, pixel by pixel into another offscreen canvas with the
// new size.
var widthScaled = img.width * scale;
var heightScaled = img.height * scale;
var orig = document.createElement('canvas');
orig.width = img.width;
orig.height = img.height;
var origCtx = orig.getContext('2d');
origCtx.drawImage(img, 0, 0);
var origPixels = origCtx.getImageData(0, 0, img.width, img.height);
var scaled = document.createElement('canvas');
scaled.width = widthScaled;
scaled.height = heightScaled;
var scaledCtx = scaled.getContext('2d');
var scaledPixels = scaledCtx.getImageData( 0, 0, widthScaled, heightScaled );
for( var y = 0; y < heightScaled; y++ ) {
for( var x = 0; x < widthScaled; x++ ) {
var index = (Math.floor(y / scale) * img.width + Math.floor(x / scale)) * 4;
var indexScaled = (y * widthScaled + x) * 4;
scaledPixels.data[ indexScaled ] = origPixels.data[ index ];
scaledPixels.data[ indexScaled+1 ] = origPixels.data[ index+1 ];
scaledPixels.data[ indexScaled+2 ] = origPixels.data[ index+2 ];
scaledPixels.data[ indexScaled+3 ] = origPixels.data[ index+3 ];
}
}
scaledCtx.putImageData( scaledPixels, 0, 0 );
return scaled;
}
Read the article through, the presence of retina displays and mobile safari may add additional complexity to rendering the correct size pixel art. Although with iOS7's mobile safari this may be rectified.
I suggest you to use an svg image, as that will be scalable and get you what you are looking for.
You can read more about the same from the below link.
https://developer.mozilla.org/en/docs/SVG_In_HTML_Introduction
Hope this helps.
Are you looking for this? <img src="http://i.imgur.com/9FLj6Uk.png width="32" height="32">
check fiddle

HTML5: Inverse text-color on canvas

I want to draw text on a canvas in the inverse color of the background (to make sure the text is readible no matter the background color). I believe in oldskool bitblt-ing, this was an XOR operation.
How to do this?
Update: most of the newer browsers now support the blending mode "difference" which can achieve the same result.
context.globalCompositeOperation = "difference";
Updated demo.
Old answer:
One should think that the XOR mode for composition would do this, but unfortunately canvas' XOR only XORs the alpha bits.
By applying the following code we can however receive a result such as this:
You can make an extension to the canvas like this:
CanvasRenderingContext2D.prototype.fillInversedText =
function(txt, x, y) {
//code - see below
}
Now you can call it on the context as the normal fillText, but with a slight change:
ctx.fillInversedText(txt, x, y);
For this to work we do the following first - measure text. Currently we can only calculate width of text and then assume the height. This may or may not work well as fonts can be very tall and so forth. Luckily this will change in the future, but for now:
var tw = this.measureText(txt).width;
var th = parseInt(ctx.font, '10');
th = (th === 0) ? 10 : th; //assume default if no font and size is set
Next thing we need to do is to setup an off-screen canvas to draw the text we want ot invert:
var co = document.createElement('canvas');
co.width = tw;
co.height = th;
Then draw the actual text. Color does not matter as we are only interested in the alpha channel for this canvas:
var octx = co.getContext('2d');
octx.font = this.font;
octx.textBaseline = 'top';
octx.fillText(txt, 0, 0);
Then we extract the pixel buffers for the area we want to draw the inverted text as well as all the pixels for the off-screen canvas which now contains our text:
var ddata = this.getImageData(x, y, tw, th);
var sdata = octx.getImageData(0, 0, tw, th);
var dd = ddata.data; //cache for increased speed
var ds = sdata.data;
var len = ds.length;
And then we invert each pixel where alpha channel for pixel is greater than 0.
for (var i = 0; i < len; i += 4) {
if (ds[i + 3] > 0) {
dd[i] = 255 - dd[i];
dd[i + 1] = 255 - dd[i + 1];
dd[i + 2] = 255 - dd[i + 2];
}
}
Finally put back the inverted image:
this.putImageData(ddata, x, y);
This may seem as a lot of operations, but it goes pretty fast.
Demo (warning if you are sensitive to flicker)
(the psychedelic background is just to have some variations as fiddle needs external images and most are prevented by CORS when we use pixel manipulation).
I've removed my old answer, as it did not solve the question. As of recently, there are new globalCompositeOperations that do all kinds of great things. I've created an example that shows how to obtain inverted text. In case that link breaks, the method is essentially this:
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "white";
//draw inverted things here
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

Is there a way to dynamically extend the html5 canvas without clearing what's drawn on it?

see this
when the output reaches the bottom of the page, i'd like the canvas to automatically extend so that it can keep going. I tried setting the canvas.height property, but it clears the window. Is there any way to do this?
What I do:
create dummy canvas with same size as your canvas.
dummyCanvas.getContext('2d').drawImage(yourCanvas, 0, 0);
newCanvas = recreate(yourCanvas);
newCanvas.getContext('2d').drawImage(dummyCanvas);
Not very pretty, especially in your situation where it would require you recreating the canvas 50+ times per second... Interested in seeing other answers... It works for me because I just resize the canvas when the clientWidth/clientHeight changes [window.onresize]
I know this is sort of old now, however:
You don't need to recreate the canvas as ItzWarty explaines. You can do this:
<html>...
<canvas id="canvas"></canvas>
<canvas id="buffer" style="display:none;"></canvas>
...
</html>
Then this would be your javascript:
var canvas = document.getElementById('canvas');
var buffer = document.getElementById('buffer');
window.onresize = function(event) {
var w = $(window).width(); //Using jQuery for easy multi browser support.
var h = $(window).height();
buffer.width = w;
buffer.height = h;
buffer.getContext('2d').drawImage(canvas, 0, 0);
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(buffer, 0, 0);
}
Here you only change the size of the canvases, and you copy over the image. I am not sure, but I believe the performance is a bit better, and it is in my opinion simpler and easier to understand.