how to draw on a image background using canvas? - javascript

What is wrong with my code.I am trying to load the image background on a canvas and then draw few rectangles on the image canvas.my image is not showing up on the canvas or either is it being completely overwritten my rectangles.
I have followed this SO question, but still, it happens.
//Initialize a new Box, add it, and invalidate the canvas
function addRect(x, y, w, h, fill) {
var rect = new Box;
rect.x = x;
rect.y = y;
rect.w = w
rect.h = h;
rect.fill = fill;
boxes.push(rect);
invalidate();
}
// holds all our rectangles
var boxes = [];
// initialize our canvas, add a ghost canvas, set draw loop
// then add everything we want to intially exist on the canvas
function drawbackground(canvas,ctx,onload){
var img = new Image();
img.onload = function(){
// canvas.width = img.width;
// canvas.height = img.height;
ctx.drawImage(img);
//addRect(200, 200, 200, 200, '#FFC02B');
onload(canvas,ctx);
};
img.src = "https://cdnimages.opentip.com/full/VLL/VLL-LET-G.jpg";
}
function init() {
// canvas = fill_canvas();
canvas = document.getElementById('canvas');
HEIGHT = canvas.height;
WIDTH = canvas.width;
ctx = canvas.getContext('2d');
ghostcanvas = document.createElement('canvas');
ghostcanvas.height = HEIGHT;
ghostcanvas.width = WIDTH;
gctx = ghostcanvas.getContext('2d');
// make draw() fire every INTERVAL milliseconds
setInterval(draw, INTERVAL);
// set our events. Up and down are for dragging,
// double click is for making new boxes
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
canvas.ondblclick = myDblClick;
// add custom initialization here:
drawbackground(canvas,ctx);
//context.globalCompositeOperation = 'destination-atop';
// add an orange rectangle
addRect(200, 200, 200, 200, '#FFC02B');
// add a smaller blue rectangle
addRect(25, 90, 250, 150 , '#2BB8FF');
}
//wipes the canvas context
function clear(c) {
c.clearRect(0, 0, WIDTH, HEIGHT);
}
...

As the Image loads always asynchronously, and you draw your rects synchronously after drawbackground() call, you will get a canvas with only image on it.
You need to create function which will pe passed as third argument to drawbackground, and call addRect in this function instead of drawbackground
PS:
Your code should throw an exception because
onload(canvas,ctx);
will try to call undefined as a function

Related

Image isn't drawn after canvas is cleared (html5 canvas)

I am trying to make a variant of the boomshine game in javascript and everything works when I draw a circular shape with the arc function. However when i try to replace the arc function with the drawImage function to use a coin image instead of a circular shape I start having problems when I clear the canvas to delete the previous drawn circular shapes. If I don't clear the canvas before rendering the images, the images are drawn on the canvas except the old images are still on the canvas. But when i do clear the canvas before rendering the images again, nothing is drawn on the canvas.
I have included screenshots, the links are below.
This is how I clear the canvas:
var ctx = game.context;
ctx.fillStyle = "darkgray";
ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
This is how i draw the image:
function drawImageBall(x,y,radius,startAngle,color)
{
var img = document.createElement('img');
img.src = 'img/coin-icon.png';
var tmpCtx= game.context;
var ax = x-radius;
var ay = y-radius;
img.onload = function() {
tmpCtx.save();
tmpCtx.beginPath();
tmpCtx.arc(x, y, radius, 0, Math.PI * 2, true);
tmpCtx.closePath();
tmpCtx.clip();
tmpCtx.drawImage(img, ax, ay, img.width, img.height);
tmpCtx.beginPath();
tmpCtx.arc(0, 0, radius, 0, Math.PI * 2, true);
tmpCtx.clip();
tmpCtx.closePath();
tmpCtx.restore();
};
}
Clearing canvas (screenshot)
Without clearing canvas (screenshot)
Keep in mind that downloading the img will take some time.
During that downloading time, Javascript does not stop(!). Instead JS will continue executing any following code. This is causing your unexpected problems.
So download the img just once at the start of your app. That way your drawImage will be done in the order that you expect because there will be no delay while your image is downloading.
Using your code, I maked some changes, I removed the tmpTcx.clip(), look the fidlle. Tip: For performace questions you don't need load the image every time that you want write the canvas.
Poor Example: https://jsfiddle.net/wf4z0d2h/1/
function clearCanvas(){
var ctx = game.context;
ctx.fillStyle = "darkgray";
ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
}
function drawImageBall(x,y,radius,startAngle,color)
{
if(x == undefined){x = 100;}
if(y == undefined){y = 100;}
if(radius == undefined){radius = 40;}
//var img = document.createElement('img');
//img.src = 'img/coin-icon.png';
//img.src = "http://ps2.lansa.com/images/icons/normal/256/coin_256.png";
var tmpCtx= game.context;
var ax = x-radius;
var ay = y-radius;
//img.onload = function() {
tmpCtx.save();
tmpCtx.beginPath();
tmpCtx.arc(x, y, radius, 0, Math.PI * 2, true);
tmpCtx.stroke(); // Draw it
tmpCtx.closePath();
//tmpCtx.clip();
tmpCtx.drawImage(img, ax, ay, img.width, img.height);
//tmpCtx.beginPath();
//tmpCtx.arc(0, 0, radius, 0, Math.PI * 2, true);
////tmpCtx.clip();
//tmpCtx.stroke(); // Draw it
//tmpCtx.closePath();
//tmpCtx.restore();
//};
}
var img = document.createElement('img');
//img.src = 'img/coin-icon.png';
img.src = "http://ps2.lansa.com/images/icons/normal/256/coin_256.png";
//drawImageBall();
img.onload = function(){
x = 0;
y = 0;
setInterval(function(){
x = x+10;
y = y+10;
clearCanvas();
drawImageBall(x,y);
},300);
}

Pattern gets shifted when painting at the bottom edge of the canvas

I would like to paint a repeating grass pattern at the bottom of a canvas. The image does repeat, but it's vertically shifted.
The pattern is based on a 192x50 image:
I've noticed that if I paint from the y-coordinates 50, 100, 150, and so on, the pattern is displayed correctly. It doesn't work at other coordinates.
The resulting canvas has a vertically shifted grass pattern:
I don't know why it gets shifted like that.
Below is my code.
HTML:
<canvas id="myCanvas" style="display: block;">
</canvas>
JavaScript:
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
// Grass Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "img/grass.png";
I do the following in a loop:
if (bgReady) {
ctx.drawImage(bgImage,0, canvas.height -50,192,50);
var ptrn = ctx.createPattern(bgImage, "repeat"); // Create a pattern with this image, and set it to repeat".
ctx.fillStyle = ptrn;
ctx.fillRect(0,canvas.height - bgImage.height,canvas.width, 50); // context.fillRect(x, y, width, height);
}
I tried to put your code in jsFiddle and it seems to work as expected:
var canvas = document.getElementById('myCanvas');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
// Grass Background Image
var bgImage = new Image();
bgImage.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(bgImage,0, canvas.height -50,192,50);
var ptrn = ctx.createPattern(bgImage, "repeat"); // Create a pattern with this image, and set it to repeat".
ctx.fillStyle = ptrn;
ctx.fillRect(0,canvas.height - bgImage.height,canvas.width, 50); // context.fillRect(x, y, width, height);
};
bgImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAAAzCAYAAADMxHf3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABbNSURBVHhe7ZzJch3JdYb9FO4mCYAAMQ8cJG/ssBWywxFsTnoCNkESw72YSUpbh7pBgJjvxTyR7PYbeuOdNun/O5mnmEChFaLVYthdtTiRWVk5nP8vnCGz6uLv/uu//xRyub3xm3Bv71/D3dZvw739fwt3278Nd7Z+Y0L72Lt/Nrm9/i9F+bn9WcNL+vk9xvo8jM3no70Ym3Q0OVTfrL9dI36fNpeszdaScO36Fuu4fklo4x59uec4vC/trneN/+fFXwjXqe3n1t1L2twOrjQMhE6uqA90BQqgKwn0Z/b3axPWy0rGm5IJeE6KrZPW8H4m/sfhfS/9sRRzXepnuroemdCftdDd+/gcdo9+6b7pjV7olHTjmr41/r8ev5d/S91d6O92UDKMYrAvlIBeAJjAjXz3TxdB/oX9L4/xNoTx6OCSP9iiLRFjhCWijDi/9rb8XtbmcyBGEHpIZ9eL+5R+jxLxcdS99L4uNf6fGf8X1J353Q7KhpEpZoO5TmBzACZ4AMnn9i/qWTukoZzNleYoCJH4GnbvUt360NdJ9HqSX538+6f2fK40R06O6+DEUbq4Lojfz/WxNq6Zs8b/CV+G83Pxf1HdVbodXGkY1imVLEYJAOoFmEw+t7+1JzJcaDMRocxVABEhDoJ5SwSpvejPH4KXTqbXU3l5nIvr7uJzUqKTzYuk9f2ej83nqPH/vPi/pO5uByXDYFAOkIn9+qcAfm7/0eVPhAz/8R+LOn0Y62IAnIyMEAOYiPI+DrggEvE2rzvBaR57CGluX5M218PvFfMkudxu42r8xXi/zrEj/xv8X1J3xO3g6lSKhdWZhaxMkoMEoJef2x8SnBwnht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gz7R8U/dp56GxBv/GhVBp3kn55mbjlhEQ88/UZrlnJArsNf5q43c7uNIw6MRRHHkh4KmzGJ6AHO9M4KkT1rBmFGtLsQNdx+/aZc3qb/cU1vA+LM6rd3sDKYlvHEcDH3TxYoWfLfKTQ75+JAQSNgmz2/IEkES+CXi8Dw8Mj7Cta/sgjH663pgZ1lgRISEl4B4hc13eYksbr1V5Dk5aePCcUCArCq/LEwMWVpcnR2r8FcfvdlAyjHVZGAPYUPHKndwQD4A3YLMDKZATTykU7pQXsinaW1SoWxrQpolPg9m8YcExfPIDdELamqyUcGbhTcpyhrys3M7Ayfo5liOMkvPx4Rjhk3BKuIQUe2mja3JI8knAQwp5JqRYWFVY5uUQIZrf9eIhIIIzbEIqIZzNZHumx0jCY4CX/JMjvBp/tfG7HZQMo5ZaavlT+B+r9fQ60AaG/QAAAABJRU5ErkJggg==";
https://jsfiddle.net/or68kcpc/
The error must be somewhere else.
The problem is that the pattern is calculated starting from the top left corner of the canvas. If you paint starting at a canvas y-coordinate that isn't an integer multiple of the image height, the visible portion of the pattern won't start at the top of the image.
To fix this, shift the drawing context down before painting with the pattern, then paint the pattern at a location shifted up, then shift the context back up:
var shiftY = canvas.height % image.height;
context.translate(0, shiftY);
context.fillRect(0, canvas.height - image.height - shiftY,
canvas.width, image.height);
context.translate(0, -shiftY);
Run the snippet below to see a demonstration. The canvas height is 120, which means that we start painting from the y-coordinate 120 - 50 = 70, which is not a multiple of 50.
To correct for this, we shift the context down by 120 % 50 = 20 and then shift the painting location up by 20. Thus, the pattern gets painted on the shifted context at the y-coordinate (70 - 20) = 50, which is a multiple of the image height.
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
canvas.height = 120;
canvas.width = 500;
var image = new Image();
image.src = 'http://i.stack.imgur.com/2bfPb.png';
image.onload = function () {
var pattern = context.createPattern(image, "repeat");
context.fillStyle = pattern;
var shiftY = canvas.height % image.height;
context.translate(0, shiftY);
context.fillRect(0, canvas.height - image.height - shiftY,
canvas.width, image.height);
context.translate(0, -shiftY);
};
#myCanvas {
border: 1px solid #666;
}
<canvas id="myCanvas"></canvas>
Let me make one more observation. The loop in your code is inefficient and the bgReady flag is unnecessary because you can run the painting code in the image.onload function, as I have done in my snippet.

Re-fill area of erased area for canvas

I am trying to fill color in image using below code snippet for filling color on Image of canvas . Its successfully filling color in canvas. Now I am trying to erase filled color on touch of user using this code snippet for erasing color on Image of canvas . Its erasing color & setting transparent area on that touched position. Now I want to refill that area on user touch with colors but its not allowing me to color on that because of transparent pixels. So Is there any way to refill pixels with color Or Is there any other way to erase color from image of canvas ? Any reply will be appreciated.
code snippet for filling color on Image of canvas
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/1alt1303g9zpemd/UFBxY.png";
function draw(color) {
ctx.drawImage(img, 0, 0);
}
canvas.onclick = function(e){
var rect = canvas.getBoundingClientRect();
var x = e.clientX-rect.left,
y = e.clientY-rect.top;
ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(x-5,y-5,10,0,2*Math.PI);
ctx.fill();
}
code snippet for erasing color on Image of canvas
(function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 10; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 531, 438, '#ddd');
})();
Warning untested code!
// create a clipping region using your erasing rect's x,y,width,height
context.save();
context.beginPath();
context.rect(erasingRectX,erasingRectY,erasingRectWidth,erasingRectHeight);
context.clip();
// redraw the original image.
// the image will be redrawn only into the erasing rects boundary
context.drawImage(yourImage,0,0);
// compositing: new pixels draw only where overlapping existing pixels
context.globalCompositeOperation='source-in';
// fill with your new color
// only the existing (clipped redrawn image) pixels will be colored
context.fillStyle='red';
context.fillRect(0,0,canvas.width,canvas.height);
// undo the clipping region
context.restore();

How to embed string in a background image?

I am trying to make a scratch card looks like
Basically I have a gray layer to scratch and it will reveal the red image.
Now I have set up the canvas and ctx is for the gray layer, but the background is fixed.
I want to have the "12345" be a variable to embed in the background,
which means I can have different number in the background image.
Here is the function I have for the scratch card.
(addEventlistener is just used for scratching the gray layer)
function bodys(height,width){
var img = new Image();
var canvas = document.querySelector('canvas');
canvas.style.position = 'absolute';
img.addEventListener('load',function(e){
var ctx;
var w = width, h = height;
var offsetX = canvas.offsetLeft, offsetY = canvas.offsetTop;
var mousedown = false;
function layer(ctx){
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, w, h);
}
function eventDown{
...
}
canvas.width=w;
canvas.height=h;
canvas.style.backgroundImage='url('+img.src+')';//here is the background image I use
ctx=canvas.getContext('2d');
ctx.fillRect(0, 0, w, h);
layer(ctx);
ctx.globalCompositeOperation = 'destination-out';
canvas.addEventListener{
...
}
});

Rotate canvas 90 degrees clockwise and update width height

Say we have a canvas:
<canvas id="one" width="100" height="200"></canvas>
And on a button click the canvas gets rotated 90 degrees clockwise (around the center) and the dimensions of the canvas get also updated, so in a sense it looks like this afterwards:
<canvas id="one" width="200" height="100"></canvas>
Note that the id of the canvas is the same.
Imagine simply rotating an image clockwise without it being cropped or being padded.
Any suggestions before I do it the long way of creating a new canvas and rotating and copying pixel by pixel?
UPDATE sample code with suggestion from comments still not working:
function imageRotatecw90(){
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var myImageData = context.getImageData(0,0, cw,ch);
context.save();
context.translate(cw / 2, ch / 2);
context.rotate(Math.PI/2);
context.putImageData(myImageData, 0, 0);
context.restore();
canvas.width=ch;
canvas.height=cw;
}
FiddleJS
Look at this DEMO.
To achieve the results seen in demo, I made use of canvas.toDataURL to cache the canvas into an image, then reset the canvas to their new dimensions, translate and rotate the context properly and finally draw the cached image back to modified canvas.
That way you easily rotate the canvas without need to redraw everything again. But because anti-aliasing methods used by browser, each time this operation is done you'll notice some blurriness in result. If you don't like this behavior the only solution I could figure out is to draw everything again, what is much more difficult to track.
Here follows the code:
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
// Sample graphic
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
// create button
var button = document.getElementById("rotate");
button.onclick = function () {
// rotate the canvas 90 degrees each time the button is pressed
rotate();
}
var myImageData, rotating = false;
var rotate = function () {
if (!rotating) {
rotating = true;
// store current data to an image
myImageData = new Image();
myImageData.src = canvas.toDataURL();
myImageData.onload = function () {
// reset the canvas with new dimensions
canvas.width = ch;
canvas.height = cw;
cw = canvas.width;
ch = canvas.height;
context.save();
// translate and rotate
context.translate(cw, ch / cw);
context.rotate(Math.PI / 2);
// draw the previows image, now rotated
context.drawImage(myImageData, 0, 0);
context.restore();
// clear the temporary image
myImageData = null;
rotating = false;
}
}
}
Rotation
Note it is not possible to rotate a single element.
ctx.save();
ctx.rotate(0.17);
// Clear the current drawings.
ctx.fillRect()
// draw your object
ctx.restore();
Width/height adjustment
The only way I ever found to properly deal with display ratios, screen sizes etc:
canvas.width = 20;// DO NOT USE PIXELS
canvas.height = 40; // AGAIN NO PIXELS
Notice I am intentionally not using canvas.style.width or canvas.style.height. Also for an adjustable canvas don't rely on CSS or media queries to do the transformations, they are a headache because of the pixel ratio differences. JavaScript automatically accounts for those.
Update
You also have to update the width and the height before you draw. Not sure what you are trying to achieve, but I guess this isn't a problem:
Demo here
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
canvas.width = 200;
canvas.height = 400;
// Sample graphic
context.beginPath();
context.rect(10,10,20,50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
var myImageData = context.getImageData(0, 0, cw, ch);
context.save();
context.translate(cw / 2, ch / 2);
context.putImageData(myImageData, 0, 0);
context.rotate(0.20);
If you want to rotate an image by 90 degrees this might be helpful:
export const rotateBase64Image = async (base64data: string) => {
const image = new Image();
image.src = base64data;
return new Promise<string>((resolve, reject) => {
image.onload = function () {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("cannnot get context '2d'");
canvas.width = image.height;
canvas.height = image.width;
ctx.setTransform(0, 1, -1, 0, canvas.width, 0); // overwrite existing transform
ctx!.drawImage(image, 0, 0);
canvas.toBlob((blob) => {
if (!blob) {
return reject("Canvas is empty");
}
const fileUrl = window.URL.createObjectURL(blob);
resolve(fileUrl);
}, "image/jpeg");
};
});
};
If you don't have image in base64 format you can do it like this:
const handleRotate = async () => {
const res = await fetch(link);
const blob = await res.blob();
const b64: string = await blobToB64(blob);
const rotatedImage = await rotateBase64Image(b64)
setLink(rotatedImage);
}
Here is my blobTob64 function:
export const blobToB64 = async (blob) => {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
};

Categories

Resources