HTML5 Canvas - Repeat Canvas Element as a Pattern - javascript

I have a 64x64 canvas square element which I want to repeat in x- and y-directions to fill the page. I've found many explanations on how to do this with an image, but none explaining how to do it with a canvas element. Here is my code so far:
$(document).ready(function(){
var canvas = document.getElementById('dkBg');
var ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
ctx.fillStyle = 'rgb(0,0,0)';
//I want the following rectangle to be repeated:
ctx.fillRect(0,0,64,64);
for(var w=0; w<=64; w++){
for(var h=0; h<=64; h++){
rand = Math.floor(Math.random()*50);
while(rand<20){
rand = Math.floor(Math.random()*50);
}
opacity = Math.random();
while(opacity<0.5){
opacity = Math.random();
}
ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
ctx.fillRect(w,h,1,1);
}
}
});
The thing is, I don't want all of the random numbers/etc to be regenerated. I just want to tile the exact same square to fit the page. Is this possible?
Here is a fiddle: http://jsfiddle.net/ecMDq/

Doing what you want is actually super easy. You do not need to use images at all. The createPattern function accepts an image or another canvas! (Or a video tag, even)
All you have to do is make a canvas that is only 64x64 large and make the pattern on it. Let's call this canvas pattern. You only have to make your design once.
Then with the context of the main canvas we can do:
// "pattern" is our 64x64 canvas, see code in fiddle
var pattern = ctx.createPattern(pattern, "repeat");
ctx.fillStyle = pattern;
Working example using your code to make the pattern, then repeating it onto a 500x500 canvas:
http://jsfiddle.net/tGa8M/

You can get the base64 version of your image using the toDataURL() method of the canvas element.
From there it's as simple as setting the background-image of your page to the string "url(" + base64 + ")"
Here is a working example: http://jsfiddle.net/ecMDq/1/
$(document).ready(function(){
var canvas = document.getElementById('dkBg');
var ctx = canvas.getContext('2d');
ctx.canvas.width = 64; //window.innerWidth;
ctx.canvas.height = 64; //window.innerHeight;
ctx.fillStyle = 'rgb(0,0,0)';
//I want the following rectangle to be repeated:
ctx.fillRect(0,0,64,64);
for(var w=0; w<=64; w++){
for(var h=0; h<=64; h++){
rand = Math.floor(Math.random()*50);
while(rand<20){
rand = Math.floor(Math.random()*50);
}
opacity = Math.random();
while(opacity<0.5){
opacity = Math.random();
}
ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
ctx.fillRect(w,h,1,1);
}
}
document.documentElement.style.backgroundImage =
'url(' +canvas.toDataURL() + ')';
});
Note that you need to make the canvas 64x64 because that's the size of your source image.
You can also now make the canvas display:none, or even remove it from the dom completely because it's only acting as a source for the background-image.
Also, what on earth is up with those while loops?
while(rand<20){
rand = Math.floor(Math.random()*50);
}
It looks like you're trying to enforce a minimum value. Just use this:
rand = Math.floor(Math.random() * (50-20) + 20);

Related

How to replace specific color range from a image?

Is there any method to replace/remove colors by color range in Javascript, Opencv or anything else that can be operated on website?
As the above image. Is that possible to replace all the white color(It can be white or near white colors) with transparent color? Any suggestion would be appreciated.
With imagemagick this can be done quickly.
convert input.jpg -fuzz 6% -transparent white output.png
The value of -fuzz 6% can be adjusted to match "near white" thresholds.
Note: The format of JPEG has changed to PNG; which, supports transparency.
You could create a canvas and draw that image onto it, that way you're able to get pixel colors and manipulate them. (And also save the result)
This might lead you somewhere to start with. If you require further help, just comment.
EDIT: Little sample of what this should work like:
//Sets up canvas containing the image:
var img = document.getElementById("image");
img.crossOrigin = "Anonymous";
img.src = "https://i.imgur.com/X1fKQsK.jpg";
loadedBefore = false;
img.onload = function(){
if(loadedBefore) return;
else loadedBefore = true;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data; //Gets color of coordinate (with 1 pixel in size)
if(color[0] > 250 && color[1] > 250 && color[2] > 250){ //Checks if color is pretty white
color[3] = 0; //Sets alpha to 0 -> Makes color transparent
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL(); //Set image to display canvas content / update image
console.log("done!");
}
<img id="image"/>
You can apparently not just load an image from some other website and modifiy it in the canvas, unless you set img.crossOrigin = "Anonymous" and the other website allows it. I got no clue on what exactly happens there, I just know that it works with imgur.com. (That's why everything's in the onload function now)
The loadedBefore stuff is because StackOverflow apparently calls the img.onload function pretty often, you won't have this issue if you use your own image so you don't need the crossOrigin and onload stuff.....
Just a function to do the stuff:
function whiteToTransparent(img){
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data;
if(color[0] > 250 && color[1] > 250 && color[2] > 250){
color[3] = 0;
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL();
}

HTML 5 canvas drawing image not showing css

When I try to draw an image on a canvas with a pre-loaded image with css like:
img.style.backgroundColor="red";
ctx.drawImage(img,0,0,100,100);
I find that the image is being drawn as it would appear without the css. Do HTML canvases support css? If not is there a way to overlay a png with transparency with a color only on the pixels that are not transparent?
Can you specify more about our requirement?
You can not set the background colour of an image which is going to draw directly from the canvas. if you altering a color, it will reflect in the source image.
You have to make it from the source element. If you want to fill the box size with some color, you could use fillStyle of the ctx before draw.
Have a look at the example here on w3schools that will get you started on how to load the image and copy it into the canvas. If you don't need the original image to be shown on the page then add 'style="display:none;"' to the img tag. To tint the image have a look at globalAlpha in combination with a filled rect - something along these lines:
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ff0000";
ctx.fill();
ctx.drawImage(img, 10, 10);
};
Canvas do not render css no matter what css you use for image it will always render plain image unless you draw border or background by yourself
It is possible to overlay the image drawn on a canvas by analyzing each pixel of the drawn image and then overlaying a 1x1 rectangle with the desired color. Here is an example of how to do so:
function overlayColor(img,x,y,a,r,g,b,drawWidth,drawHeight){
//create a canvas in memory and draw the image there to analyze it
var tmpCanvas = document.createElement('canvas');
var context = tmpCanvas.getContext('2d');
tmpCanvas.width = drawWidth;
tmpCanvas.height = drawHeight;
context.drawImage(img,0,0,drawWidth,drawHeight);
let pData = new Array();
for (let i = 0; i < tmpCanvas.width; i++){
for (let j = 0; j < tmpCanvas.height; j++){
if (context.getImageData(i, j, 1, 1).data[3] != 0){//if the pixel is not transparent then add the coordinates to the array
pData.push([i,j]);
}
}
}
//then every pixel that wasn't transparent will be overlayed with a 1x1 rectangle of the inputted color
//drawn at the (x,y) origin which was also given by the user
//this uses ctx, the context of the canvas visible to the user
ctx.fillStyle="rgba(" + r + "," + g + "," + b + "," + a + ")";
for (let i = 0; i < pData.length; i++){
ctx.fillRect(x + pData[i][0],y + pData[i][1],1,1);
}
}
Since the function takes an x and y value the image given by the user will be analyzed and overlayed only on pixels that are not transparent at the coordinate given by the user with the rgba value also given. I have found that this process can result in some lag but it could be overcome by saving the pData array and using the second half of the function to draw the array on screen again.

how to create a canvas dynamically in javascript

I have a canvas that you can draw things with mouse.. When I click the button It has to capture the drawing and add it right under the canvas, and clear the previous one to draw something new..So first canvas has to be static and the other ones has to be created dynamically with the drawing that I draw .. What should I do can anybody help
here is jsfiddle
http://jsfiddle.net/dQppK/378/
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
painting = false,
lastX = 0,
lastY = 0;
You can create a new canvas the same way you’d create any element:
var newCanvas = document.createElement('canvas');
Then you can copy over your old canvas:
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
oldCanvas.parentNode.replaceChild(newCanvas, oldCanvas);
ctx = newCanvas.getContext('2d');
But if you’re just looking to clear your drawing surface, what’s wrong with clearRect?
ctx.clearRect(0, 0, canvas.width, canvas.height);
Or, in your case, another fillRect. Updated demo
here's the function i use for this, it is part of a library i made and use to ease a few things about canvas.
I just put it on github in case other function might be be of use, i'll have to make a readme later...
https://github.com/gamealchemist/CanvasLib
with namespaceing removed, the code is as follow to insert a canvas :
// insert a canvas on top of the current document.
// If width, height are not provided, use all document width / height
// width / height unit is Css pixel.
// returns the canvas.
insertMainCanvas = function insertMainCanvas (_w,_h) {
if (_w==undefined) { _w = document.documentElement.clientWidth & (~3) ; }
if (_h==undefined) { _h = document.documentElement.clientHeight & (~3) ; }
var mainCanvas = ga.CanvasLib.createCanvas(_w,_h);
if ( !document.body ) {
var aNewBodyElement = document.createElement("body");
document.body = aNewBodyElement;
};
document.body.appendChild(mainCanvas);
return mainCanvas;
}

canvas toDataURL not returning a complete image

I'm building a jQuery plugin which watermarks images (and yes, i'm well aware of the multitudinal drawbacks of a javascript/html5 watermarking system but just ignore that for now.) The basic method for each image is:
paste the image to the background of a canvas
add the data for a watermark image over that,
replace the src of the original image with that of the canvas (which now contains the watermark.)
Now it appears to work fine if I replace the image element with the canvas itself.. all of the elements appear on the canvas. But when I get the dataURL of the canvas, everything but the last image drawn onto it appears. I wouldn't even mind except this plugin also needs to replace the links to images as well, and so replace the hrefs with data urls (with the watermark.)
This is the current code:
(function($){
$.fn.extend({
cmark: function(options) {
var defaults = {
type: 'image',
content: 'watermark.png',
filter: 'darker',
scale:300,
box: {
top : 0.5,
left : 0.5,
width : 0.75,
height : 0.75,
bgcolor : '#000000',
bgopacity : 0.5,
fgopacity : 1
},
callback_unsupported: function(obj){
return obj;
}
}
var getScale = function(w, h, scale){
ratio = Math.min(scale/w, scale/h);
scalew = Math.round(ratio*w);
scaleh = Math.round(ratio*h);
return [scalew,scaleh];
}
var options = $.extend(defaults, options);
return this.each(function() {
obj = $(this);
canvas = document.createElement('canvas');
if(!window.HTMLCanvasElement){
return options.callback_unsupported(obj);
}
/* if selecting for images, reset the images. Otherwise,
we're replacing link hrefs with data urls. */
if(obj.attr('src')){
target_img = obj.attr('src');
}
else if (obj.attr('href')){
target_img = obj.attr('href');
}
// get the filetype, make sure it's an image. If it is, get a mimetype. If not, return.
ftype = target_img.substring(target_img.lastIndexOf(".")+1).toLowerCase();
canvasbg = new Image();
canvasbg.onload = function(){
iw = canvasbg.width;
ih = canvasbg.height;
scale = getScale(iw, ih, options.scale);
iw = scale[0];
ih = scale[1];
canvas.setAttribute('width', iw);
canvas.setAttribute('height', ih);
ctx = canvas.getContext('2d');
/* define the box as a set of dimensions relative to the size of the image (percentages) */
bw = Math.round(iw * options.box.width);
bh = Math.round(ih * options.box.height);
// for now the box will only ever be centered.
bx = Math.round((iw * options.box.top) - (bw/2));
by = Math.round(ih * options.box.left - (bh/2));
/* draw the box unless the opacity is 0 */
if(options.box.bgopacity > 0){
ctx.fillStyle = options.box.bgcolor;
ctx.globalAlpha = options.box.bgopacity;
ctx.fillRect(bx, by, bw, bh);
}
wm = new Image();
wm.onload = function(){
ww = wm.width;
wh = wm.height;
scalar = Math.max(bw, bh); // scale to within the box dimensions
scale = getScale(ww, wh, scalar);
ww = scale[0];
wh = scale[1];
ctx.globalCompositeOperation = options.filter;
ctx.drawImage(wm, bx, by, ww, wh);
}
wm.src = options.content;
ctx.drawImage(canvasbg, 0, 0, iw, ih);
obj.replaceWith(canvas);
$('body').append('<img src="'+canvas.toDataURL()+'">');
//obj.attr('src', canvas.toDataURL());
}
canvasbg.src = target_img;
});
}
})
})(jQuery);
I added a line which dumps an image with the data url directly onto the page for testing and this is what I see... on the left is the canvas element, on the right is the image with the data url:
So yeah, this has had me stumped for a couple of days now. I'm probably missing something horribly obvious but I can't see it.
... edited because the example is no longer online. sorry.
First of all, don't build a string buffer that big for a tag.
var img = new Image();
img.src = canvas.toDataURL();
$('body').append(img);
Or if you prefer:
$('body').append($('<img>').attr('src', canvas.toDataURL()))
Second, you are getting there dataURL of the canvas before you draw the watermark. The drawing happens in the wm.onload callback function, which happens when the watermark loads. That may not fire until way after canvasbg.onload fires off, which is where you get the dataURL.
So move the image append into code at the end of the wm.onload callback and you should be good.

What is leaking memory with this use of getImageData, javascript, HTML5 canvas

I am working with the 'canvas' element, and trying to do some pixel based manipulations of images with Javascript in FIrefox 4.
The following code leaks memory, and i wondered if anyone could help identify what is leaking.
The images used are preloaded, and this code fragment is called once they are loaded (into the pImages array).
var canvas = document.getElementById('displaycanvas');
if (canvas.getContext){
var canvasContext = canvas.getContext("2d");
var canvasWidth = parseInt(canvas.getAttribute("width"));
var canvasHeight = parseInt(canvas.getAttribute("height"));
// fill the canvas context with white (only at start)
canvasContext.fillStyle = "rgb(255,255,255)";
canvasContext.fillRect(0, 0, canvasWidth, canvasHeight);
// for image choice
var photoIndex;
// all images are the same width and height
var imgWidth = pImages[0].width;
var imgHeight = pImages[0].height;
// destination coords
var destX, destY;
// prep some canvases and contexts
var imageMatrixCanvas = document.createElement("canvas");
var imageMatrixCanvasContext = imageMatrixCanvas.getContext("2d");
// Set the temp canvases to same size - apparently this needs to happen according
// to one comment in an example - possibly to initialise the canvas?
imageMatrixCanvas.width = imgWidth;
imageMatrixCanvas.height = imgHeight;
setInterval(function() {
// pick an image
photoIndex = Math.floor(Math.random() * 5);
// fill contexts with random image
imageMatrixCanvasContext.drawImage(pImages[photoIndex],0,0);
imageMatrixData = imageMatrixCanvasContext.getImageData(0,0, imgWidth, imgHeight);
// do some pixel manipulation
// ...
// ...
// choose random destination coords (inside canvas)
destX = Math.floor(Math.random() * (canvasWidth - imgWidth));
destY = Math.floor(Math.random() * (canvasHeight - imgHeight));
// show the work on the image at the random coords
canvasContext.putImageData(imageMatrixData, destX, destY);
}, 500);
}
Oh.. mistake. The memory lookes OK after few test.
But there is another problem.
The size of used memory by tab process is growing when changing the src property of img elements...
Src property = canvas.getContext('2d').toDataURL('image/png') (changing each time);
I've tried to "delete img.src", remove node...
Changing imageMatrixData = ... to var imageMatrixData = ... might help a bit, but I doubt that is the full story. But as far as i can tell imageMatrixData is a global scope variable that you assign on every interval iteration, and that cannot be healthy especially with a big chunk of data :)
I know that getImageData used to memoryleak in Chrome but that was pre version 7, not sure how it is now, and seeing as you are talking about ff4 then that is probably very irrelevant.

Categories