How to embed string in a background image? - javascript

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{
...
}
});

Related

how to draw on a image background using canvas?

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

how can we grayscale a pattern image used in canvas (javascript)

created a circle context and added the pattern image to fill in that circle.how can i make that pattern image grayscaled.
Is there any idea that would help me.
code :
ctx.beginPath();
var bg = new Image();
bg.src = image;
bg = function() {
var pattern = ctx.createPattern(this, "no-repeat");
ctx.fillStyle = pattern;
};
ctx.moveTo(canvasCenterHoriz, canvasCenterVert);
ctx.arc(x, y, radius, startAngle, endAngle, direction);
ctx.lineWidth = 0;
ctx.fill();
This might not be the best way to do this, but it's pretty simple and it works.
I have attached a working example below. Here's how it works:
The pattern image is drawn in an invisible canvas. Once the image has loaded, it is drawn on the canvas with a white overlay and saturation set as the global composite operation. The canvas will now contain a grayscale version of your pattern.
The temporary canvas is then converted to an image, with its source set to the canvas data url. Maybe there's a better way to send image data between two canvases, but I haven't found one.
Once the pattern is finished, your original arc is drawn with the new pattern.
let canvas = document.getElementById('grayscale-canvas');
let ctx = canvas.getContext('2d');
function makeGrayscaleBackground(image, onready) {
var bg = new Image();
bg.src = image;
bg.onload = function() {
// Create a canvas that's not attached to the DOM
var canvas = document.createElement('canvas');
canvas.setAttribute('width', this.width);
canvas.setAttribute('height', this.height);
document.body.appendChild(canvas);
let ctx = canvas.getContext('2d');
// Draw the background image
ctx.drawImage(this, 0, 0);
// Then draw a white layer on top, with the saturation composite operation
// which will remove the color from the underlying image
ctx.globalCompositeOperation = "saturation";
ctx.fillStyle = "#FFF";
ctx.fillRect(0, 0, this.width, this.height);
onready(canvas);
};
}
function drawWithImage(image) {
makeGrayscaleBackground(image, function(patternImage) {
// Green background
ctx.fillStyle = "#3f9";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Make a repeating pattern with image we created
var pattern = ctx.createPattern(patternImage, "repeat");
// Make an arc with the pattern
let x = y = canvas.width/2;
ctx.fillStyle = pattern;
ctx.beginPath();
ctx.arc(x, y, canvas.width/2-10, 0, 2*Math.PI);
ctx.fill();
})
}
// Example pattern image
// For security reasons, the image needs to be hosted on the same server as the script!
var bgImage = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
drawWithImage(bgImage);
document.getElementById('bg').src = bgImage;
<canvas width="150" height="150" id="grayscale-canvas"></canvas><br>
Actual background image: <img id="bg"><br>
Modified background image:

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/xNoTx6O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mp+QNKL8EI8ziJSzcCmyssxHj9EEbNXkJNle08ztkPAEk0Z8N2I5wsJHk9GFFgid8O5mIEjnRkwyE7+UlCKdvJ4dFTvzxSo2/uvjdDkqGAQm8DeRDMfLHSFI8PeCNYzw+i5YZSVGbeQ8I67EQ6jmktVOSi4pMLBpSIJyjMyzdNkkzI2G1ORb4CSOfJfODEkImBLR0jQfhjSY5LuRy4kAd3fAMm5rH/p0LXkdrgIHcFOLthynyFO/SxmujwafHeBARozBqL35EDB4DT1LjrzZ+t4OSYaA0oQcrJNQdywsQmlgM8Hy5CAF2fiwCII+wyJEZJwzkovY9P2PVD0X3ZtVHnsJyVhHDd/GrsuDVxlh4Oz0WVhr8q5TbWlN5pB4C5HCGbT8/lPDzR9r2TQeRrbDc1hwQgqcgz7R8U/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();

canvas hole in html5 with image not working

I am trying to create a hole in canvas; and loading image in canvas after.
I want this canvas to contain a hole at a top layer.
I just read about counter-clockwise canvas rules and then created hole with counter clockwise position as below-
var c = document.getElementById("canvas-front");
var ctx = c.getContext("2d");
var centerX = c.width / 2;
var centerY = c.offsetTop;
var radius = 30;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI,true);//boolean true to counter-clockwise
ctx.fillStyle = 'black';
ctx.fill();
I have canvas before image in it-
After applying image in this canvas-
Canvas-
<canvas id="canvas-front" width="261" height="506"></canvas>
As you can see from both the images, I can't get this hole in canvas work.
How do I create this arc so that image doesn't overlap this.
I get this issue solved-
What I had to do-
On change of file I did empty to canvas and redrew image and then while image is being loaded
the arc is being created to counter-clockwise position-
Drawing the canvas again on image change-
var canvas = document.getElementById("canvas-front");
canvas.width = canvas.width;//blanks the canvas
var c = canvas.getContext("2d");
Creating image and giving it required src from changed input-
var img = new Image();
img.src = e.target.result;
Loading image and creating arc parallely-
img.onload = function () {
c.drawImage(img, 0, 0);
var centerX = canvas.width / 2;
var centerY = canvas.offsetTop;
var radius = 30;
c.beginPath();
c.arc(centerX, centerY, radius, 0, 2 * Math.PI, true);
c.fillStyle = 'black';
c.fill();
}

Categories

Resources