Canvas gets larger every time I use it to create a chart - html

I'm currently using Chart.JS on Phonegap and every time I make a new chart on the same Canvas, it gets twice as big. It's very strange and I don't know if I'm describing it properly. I'll clarify upon suggestions/questions, thanks guys.
Here is the javascript used to make the chart:
var ctx = $("#myChart").get(0).getContext("2d");
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
new Chart(ctx).Pie(data);
canvas.width = canvas.width
EDIT:
I don't know why this bug happens, but I fixed it by hard-setting the width and height each time:
var ctx = $("#myChart").get(0).getContext("2d");
// set canvas dimensions
ctx.canvas.width = chartWidth;
ctx.canvas.height = chartHeight;
// draw chart
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
drawChart(avgMin[1],avgMin[0], ctx);
// maintain canvas dimensions
ctx.canvas.width = chartWidth;
ctx.canvas.height = chartHeight;

Related

HTML canvas image is fading out after multiple iterations/reusing

I have a portal which is used for collecting orders from users in hand written format.
In my portal, I am using HTML canvas for getting inputs from user.
Once the user write order and submits it, I will read the drawings from the canvas and saves it into my DB.
HTML
<canvas height="750" width="768" id="userNotes"></canvas>
Javascript
var canvas = document.getElementById('userNotes');
var notesDataURL = canvas.toDataURL();
saveImageDataToDataBase (notesDataURL);
Next time when the user comes for a new order, I will draw this image back into the canvas, so that he can make modifications on the same and submit it as fresh order.
Javascript
var canvas = document.getElementById('userNotes');
var context = canvas.getContext('2d');
var img = new Image();
img.src = imageData;
context.drawImage(img, 0, 0);
Problem that I am facing is that after multiple iterations, the image starts fading out.
One observation is that fading is more at the bottom part of the image and less on the top side.
Consider the below sample images,
After 10 iterations image became like this,
Below is a JS FIddle created using sample code, in this after about 25 iterations fading will be visible(issue is visible only in tablet mentioned below).
https://jsfiddle.net/hz8r993v/
Observation:
An observation which I made is the issue is happening only in a specific tablet model, Samsung SM-P550, which is unfortunately the one my application is build for.
I am not able to reproduce this issue while using this application in my laptop, PC or another sm-p650 tablet.
Currently Only happening in all tablets of model SM-P550. Even I am confused with this observation.
I also tried disabling ImageSmoothingEnabled properties, but not helping.
Any leads/clues are appreciated.
JPEG compression quirk & rounding.
Looking at the image you provided suggests to me that you are incorrectly offsetting the image each time you render it. As you have not provided enough code for anyone to make an assessment as to why this is happening leaves us only to guess.
Lossless JPEG!
My first instinct is that you have offset the drawing or scaled it. I create the example below and offset a jpeg url of the rendered text by 0.2 pixels.
The result no blur Not a real surprise Jpegs are designed so that they can be copied. The artifacts introduced by the compression actually remove the blur introduced by the offset
Draw jpeg image 0.2 pixels down save and repeat.
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
}
}
function iterate(){
count += 1;
copy();
paste(0,0.2);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 150></canvas>
Your image clearly shows a vertical blurring so I set about finding when I can blur the image so that it over comes the Jpeg compression. Offsetting by 0.5 or more does not blur the image just scrolls pixel perfect 100 pixels (note I copy past 100 times move image 0.5 pixels down yet resulting image has moved 100 pixels. I have marked row 100)
Jpeg turns 0.5 pixel steps into 1 pixel steps
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
if(count === 100){
ctx.fillRect(0,100,canvas.width,1);
}
}
}
function iterate(){
count += 1;
copy();
paste(0,0.5);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 150></canvas>
At end redline is pixel row 100.
Seams that Jpeg compression is much better at preserving the original src image pixels than I suspected. But that does not help solve the problem.
Device specific
So is it a quirk of the device. I look up the specs and nothing stands out. I begin to suspect that you may have a canvas display scaling issues (the canvas resolution not matching the display size)
I start to set up the snippet to use differing resolutions and by shear chance I run the code at the same resolution as the samsung device mentioned in the question.
Blurring yay... but i did not change the canvas pixel scaling, all I did was change the canvas resolution.
Example of blurring.
Note that offset is 0.01 pixels (100th of a pixel)
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
}
}
function iterate(){
count += 1;
copy();
paste(0,0.01);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 1023></canvas>
Possible fix.
As there is not enough code to give a complete answer the above experiments have given me enough information to make an educated guess.
The problem is specific to the resolution 1024 height. (I have tried a few other (very limited) resolutions and could not get blurring)
The blurring does not occur at that resolution if the image is rendered at the pixel boundaries.
The possible fix.
When you render the image convert the render coordinates to integers using Math.floor(coordinate) this will ensure there is no fractional offset, even very tiny offsets that should not affect the image can be amplified by the jpeg compression when the resolution is at 1024 (and maybe some other resolutions as well).
var oldImage = new Image;
oldImage.src = "old image url";
oldImage.onload = function(){
ctx.drawImage(oldImage,Math.floor(x),Math.floor(y));
}
Hope this helps.
I am probably not experienced enough to tell you what about that tablet version, or what in your HTML/Javascript could be causing this issue. I am, however, good at problem solving, and solving puzzles.
I have two possible guesses:
Is there anything in your code, which could lead to a change in the resolution? The only reason that I think this may be part of the cause, is that because the image is being redrawn on a canvas that is the same size, any change in the image size could cause the image to become slightly pixilated. and repetitive changes in the image size would only exaggerate this change.
That is probably not the sole cause. I think that there is probably an additional cause because the issue is only present on the one specific tablet version. I am not familiar with that tablet version, but is there anything about its OS or interface that could alter the file when it is saved or redisplayed?
As a side note, it would be nice if you could provide a comparison image, just to see the change.
Hope that this at least points you in the right direction.

HTML5 Canvas image resize on Chrome & easeljs

I'm struggling to make smooth image resized in canvas in Chrome. In firefox it works well, but in Chrome I'm stuck on making it smooth.
Here is the jsfiddle
http://jsfiddle.net/flashmandv/oxtrypmy/
var AVATAR_SIZE = 100;
var WHITE_BORDER_SIZE = 3;
var stage = new createjs.Stage("canvas");
var avCont = new createjs.Container();
stage.addChild(avCont);
avCont.x = avCont.y = 20;
//add white circle
var whiteBorderCircle = new createjs.Shape();
var radius = (AVATAR_SIZE+WHITE_BORDER_SIZE*2)/2;
whiteBorderCircle.graphics.beginFill("white").drawCircle(radius, radius, radius);
avCont.addChild(whiteBorderCircle);
//add avatar image mask
var avatarMask = new createjs.Shape();
avatarMask.graphics.beginFill("red").drawCircle(AVATAR_SIZE/2+WHITE_BORDER_SIZE, AVATAR_SIZE/2+WHITE_BORDER_SIZE, AVATAR_SIZE/2);
//add avatar image
var image = new Image();
image.onload = function(){
var bitmap = new createjs.Bitmap(image);
bitmap.mask = avatarMask;
var bounds = bitmap.getBounds();
bitmap.scaleX = (AVATAR_SIZE+WHITE_BORDER_SIZE*2) / bounds.width;
bitmap.scaleY = (AVATAR_SIZE+WHITE_BORDER_SIZE*2) / bounds.height;
avCont.addChild(bitmap);
stage.update();
};
image.src = 'http://files.sharenator.com/sunflowers-s800x800-423444.jpg';
Notice the jagged image
Please help
It is due to how clipping works in Chrome. Clip masks are pretty brutal in Chrome while in Firefox you get anti-aliasing along the non-straight edges.
Here is a proof-of-concept for this (run this in Chrome and in FF to see the difference):
http://jsfiddle.net/r65fcqoy/
The only way to get around this is to use composite modes instead, which basically means you need to rewrite your code unless the library you're using support this in some way.
One use of a composite mode is to use it to fill anything inside an existing drawing on the canvas.
We'll first create the filled circle we want the image to appear inside
Change comp mode to source-in and draw image
Then we go back to normal comp mode and draw the outer border
Here is an approach using vanilla JavaScript where you can control how you plug things together - this is maybe not what you're after but there is really not much option if the library as said doesn't support comp mode instead of clipping:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
img = new Image,
x = 70, y =70;
var AVATAR_SIZE = 100;
var WHITE_BORDER_SIZE = 3;
var radius = (AVATAR_SIZE+WHITE_BORDER_SIZE*2)/2;
img.onload = function() {
// first draw the circle for the inner image:
ctx.arc(x, y, AVATAR_SIZE*0.5, 0 , 2*Math.PI);
ctx.fill();
// now, change composite mode:
ctx.globalCompositeOperation = 'source-in';
// draw image in top
ctx.drawImage(img, x-AVATAR_SIZE*0.5, y-AVATAR_SIZE*0.5,
AVATAR_SIZE, AVATAR_SIZE);
// change back composite mode to default:
ctx.globalCompositeOperation = 'source-over';
// now draw border
ctx.beginPath();
ctx.arc(x, y, radius + 5, 0, 2*Math.PI);
ctx.closePath();
ctx.lineWidth = 10;
ctx.strokeStyle = '#ffa94e';
ctx.stroke();
};
img.src = 'http://i.stack.imgur.com/PB8lN.jpg';
<canvas id=canvas width=500 height=180></canvas>
Another solution to this would be in onload function to add another shape above the masked image to simply cover the jagged edges of the clipping mask

Image resize with HTML5 Canvas - Distortion

I'm working on a Webworks app where I need to resize an image for upload to a server. I'm using JQuery Mobile, the app needs to run on OS6 and up. The user can either use the camera or select an image off the device. The relevant code is as follows:
function handleOpenedFile(fullPath, blobData) {
var image = new Image();
image.src = fullPath; //path to image
image.onload = function () {
var resized = resizeMe(image); // send it to canvas
//Do stuff with the DataURL returned from resizeMe()
};
}
function resizeMe(img) {
var canvas = document.createElement('canvas');
var width = Math.round(img.width / 2);
var height = Math.round(img.height / 2);
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL("image/jpeg", 0.8);
}
I then use the Base64 in the DataURL for uploading to the server. The images get scaled but they come out garbled. Parts of the image are shifted around and colours come out strange. It's not the scaling per se that messes up the image as it comes out garbled if you draw it on the canvas without any scaling.
I've searched both SO and the BB Dev forums extensively with no luck.
Does anyone have any idea how to fix this or have an alternative suggestion for resizing an image for upload?
I've managed to solve the problem although why it works eludes me. Simply replace
return canvas.toDataURL("image/jpeg", 0.8);
with
return canvas.toDataURL();
This returns a base64 encoded string with the properly resized image without any strange visual artifacts.
Cannot help with JQuery mobile, apps running on OS6 or using Base64 in the DataURL for uploading to a server but your code for the function resizeMe does not place the canvas in the HTML document anywhere.
Required line added below.
function resizeMe(img) {
var canvas = document.createElement('canvas');
var width = Math.round(img.width / 2);
var height = Math.round(img.height / 2);
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas); //append canvas child to body <<<<-----------
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL("image/jpeg", 0.8);
}
If this extra line is missed out in the jsfiddle below you get no image at all, with it you get a scaled image properly formed. The fiddle works on my andriod smart phone.
http://jsfiddle.net/FeALQ/

html5 getImageData then putImageData results in fading image

I'm very new to Html5 and I was wondering if someone could shed some light on this:
<script type="text/javascript">
window.onload = function () {
var canvas = document.getElementById('canvas'); //682 x 111 pixel canvas
var context = canvas.getContext('2d');
var image = new Image();
image.src = "/Content/ImageTestOne/logo-for-dissolve.png"; //682 x 111 pixel image
image.onload = function () { context.drawImage(image, 0, 0); drawFrame(); };
function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
imageData = context.getImageData(0, 0, canvas.width, canvas.height);
//Do something to some pixels here that persists over time
context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(imageData, 0, 0);
};
};
</script>
According to my limited knowledge of Html5 this code should do nothing except continually display the "image". But instead the image quite rapidly burns out to almost white which suggests that the imageData is changed slightly each time it is either read from or written to the canvas...
Basically I wanted to fade the image where the mouse was located so that a background image shows through as the mouse is moved around. Is there a way around this or am I going to have to become a little more creative with the process? Is there anyway I can manipulate the "image" ImageData rather than getting it from the canvas each time?
Thanks in advance, I've tried using jpg and png and loading into DOM rather than via image.src but they all have the same issue.
Using the latest Chrome btw.
Here is the setup for the requestionAnimationFrame to handle a range of browsers with a fail over to SetTimeout:
(!window.requestAnimationFrame)
{
window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000/60);
});
}
Here is the code for the canvas
<canvas id="canvas" width="682" height="111"></canvas>
That's all the code for this.
putImageData() and getImageData() can be lossy. There's a note in the spec about this:
Due to the lossy nature of converting to and from premultiplied alpha
color values, pixels that have just been set using putImageData()
might be returned to an equivalent getImageData() as different values.
See also this related question:
Why does HTML Canvas getImageData() not return the exact same values that were just set?
I have tried also to apply this to my game where in im going to manipulate the selected pixels to have effect but It doesn't give me the expected result
here is some sample code that i used to manipulate the pixel to change
get image information and store
var img = context.getImageData(0,0, width, height)
var imgdata = img.data
var len = imgdata.length
loop to all data and manipulate pixel information
var i = 0;
for(i; i<leng; i++) {
var red = imgdata[i]
var green = imgadata[i+1]
var blue = imgdata[i+2]
var alpha = imgdata[i+3]
imgdata[i] = new value
imgdata[i+1] = new value
imgdata[i+2] = new value
imgdata[i+3] = new value
}
context.putImageData(img, 0,0)
then create animation frame to see effect
requestAnimationFrame is an experimental feature (june 2012) that uses time based frame access. The reason for this is avoid latency in animations.
I suggest you take a look at this Moz article.

How to resize the drawing of the canvas in HTML5?

I would like to resize the canvas to a smaller dimension than what it is. Here is my code:
var modelPane = document.getElementById('model_pane');
//create canvasclass="modelview"
var canvas_ = document.createElement('canvas');
canvas_.setAttribute('width', 1160);
canvas_.setAttribute('height', 500);
canvas_.setAttribute('id', 'canvas');
canvas_.setAttribute('class', 'modelview');
var ctx_ = canvas_.getContext('2d');
//draw
for (i=0;i<nodes.length;i++)
{
ctx_.strokeRect(nodes[i].x, nodes[i].y, nodes[i].width, nodes[i].height);
}
//scale
ctx_.scale(0.3,0.3);
modelPane.appendChild(canvas_);
Yet this doesn't work. Anyone know why? The canvas doesn't resize to the new dimensions.
You need to call scale first:
var ctx_ = canvas_.getContext('2d');
ctx_.scale(0.3,0.3);
//draw
for (i=0;i<nodes.length;i++)
ctx_.strokeRect(nodes[i].x, nodes[i].y, nodes[i].width, nodes[i].height);
}
Think about it, like you need to scale you canvas down. Then draw on the smaller canvas.
Example