Canvas resize image object and repeat pattern - javascript

My canvas is 500px x 500px.
I have a png image that is 500px x 500px:
I want to re-size the image to be say... 100px x 100px, and then use that re-sized image as part of defining a repeat pattern and then using that as a fillStyle to repeat across the whole canvas. This is what I do...
//...define canvas, ctx, width and height above
var image = new Image();
image.onload = function() {
_self = this;
drawBG();
}
image.src = 'img.png';
function drawBG() {
var space = ctx.createPattern(_self, 'repeat');
ctx.fillStyle = space;
ctx.fillRect(0, 0, width, height);
}
Now, this is all well and good if I want to waste my own time. See, the space image is the same size as the canvas. My question is... How do you first resize the original image(in javascript) to then later create a pattern with it?
P.S. How do you re-size an image on stack overflow? This image I have showing here is to big for it's purpose.

You can draw your image on a second offscreen canvas, with drawImage(img, x, y, resizedWidth, resizedHeight) and then use this canvas as pattern.
var ctx = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
// create an off-screen canvas
var patt = document.createElement('canvas');
// set the resized width and height
patt.width = 50;
patt.height = 50;
patt.getContext('2d').drawImage(this, 0,0, patt.width, patt.height);
// pass the resized canvas to your createPattern
drawBG(patt);
}
image.src = 'http://lorempixel.com/500/500';
function drawBG(patternCanvas) {
var space = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillStyle = space;
ctx.fillRect(0, 0, 400, 200);
}
<canvas id="canvas" width="500" height="250"></canvas>

Related

How to scale small ImageData to large HTML canvas

I am trying to put image data 100x100 to canvas 1000x1000 , but cant able to do it ,
let width=1000; //canvas width
let height=1000; //canvas height
let img_w=100; //image width
let img_h=100; //image height
let img=new Image();
img.width=img_w
img.height=img_h
img.src="./flower.jpg"
var canvas = document.getElementById('mycanvas');
var context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
let pixels,scannedimg;
img.onload=()=>{
context.drawImage(img, 0, 0,width,height );
scannedimg = context.getImageData(0, 0, img.width, img.height);
pixels=scannedimg.data
console.log(pixels)
redraw();
}
let row=4*img_w;
let col=img_h;
function redraw(){
for(let i=0;i<row;i+=4){
for(let j=0;j<col;j++){
pixels[i+j*row]=0;
pixels[i+j*row+1]=0;
pixels[i+j*row+2]=0;
//pixels[i+j*400+3]=0;
}
}
scannedimg.data=pixels;
console.log(scannedimg);
context.putImageData(scannedimg,0,0,0,0,width,height);
}
i have converted the original array into a black image array (array of zeros) , but while putting on canvas , it is still 100x100
How to scale it to 1000x1000?
i don't want to iterate through 1000x1000 and set it to zero ,
i need a computationally efficient answer
Unless you outsource the pixel calculations to a WebAssembly module a JavaScript-only approach would indeed be rather slow for a large image.
Honestly I'm not sure what you are actually doing in your code.
First your drawing an unknown-sized .jpg to a 1000x1000 canvas which - unless the .jpg is also 1000x1000 - will scale and eventually distort the source image.
let width=1000;
let height=1000;
context.drawImage(img, 0, 0, width, height);
Secondly you're obtaining the pixel data of a 100x100 region from the top-left of your 1000x1000 canvas.
let img_w=100;
let img_h=100;
img.width=img_w;
img.height=img_h;
scannedimg = context.getImageData(0, 0, img.width, img.height);
Finally in your redraw() function you're rather randomly setting some of the pixels to black and draw it back to the canvas at 1000x1000 (which doesn't work that way but I will get into it later).
Let's do it a little different. Say we have a 300x200 image. First we need to draw it to a 100x100 canvas while maintaining it's aspect ratio to get the 100x100 imagedata.
This can be done using a dynamically created off-screen <canvas> element as we don't need to see it.
Now the tricky part is the CanvasRenderingContext2D putImageData() method. I assume you were thinking that the last pair of parameters for the width & height would stretch existing pixel data to fill the region specifid by (x, y, width, height). Well that's not the case. Instead we need to - again - paint the 100x100 pixel data to a same-sized off-screen canvas (or for simlicity re-use the existing) and draw it to the final canvas using the drawImage() method.
Here's everything put together:
let pixelsWidth = 100;
let pixelsHeight = 100;
let finalWidth = 500;
let finalHeight = 500;
let tempCanvas = document.createElement('canvas');
let tempContext = tempCanvas.getContext('2d');
tempCanvas.width = pixelsWidth;
tempCanvas.height = pixelsHeight;
let pixelData;
let img = new Image();
img.crossOrigin = 'anonymous';
img.onload = (e) => {
let scale = e.target.naturalWidth >= e.target.naturalHeight ? pixelsWidth / e.target.naturalWidth : pixelsHeight / e.target.naturalHeight;
let tempWidth = e.target.naturalWidth * scale;
let tempHeight = e.target.naturalHeight * scale;
tempContext.drawImage(e.target, pixelsWidth / 2 - tempWidth / 2, pixelsHeight / 2 - tempHeight / 2, tempWidth, tempHeight);
pixelData = tempContext.getImageData(0, 0, pixelsWidth, pixelsHeight);
redraw();
}
img.src = 'https://picsum.photos/id/237/300/200';
function redraw() {
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
canvas.width = finalWidth;
canvas.height = finalHeight;
tempContext.putImageData(pixelData, 0, 0);
context.drawImage(tempCanvas, 0, 0, finalWidth, finalHeight);
}
canvas {
background: #cccccc;
}
<canvas id="canvas"></canvas>

drawing a cropped version of an image onto a canvas

I have the following html file which draws an image on the canvas.
<canvas id="canvas"width="800"height="800"></canvas>
<script>
var canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
let img = new Image()
img.src = 'https://clipartspub.com/images/circle-clipart-blue-1.jpg'
img.onload = function(){
ctx.drawImage(img,300,300,300,300)
}
</script>
It works fine, however I would like to instead draw a cropped version of this image, for example, the bottom right quarter of the image. Is this possible?
You have to use the below implementation of drawImage to achieve that
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
Check the docs here
var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "https://clipartspub.com/images/circle-clipart-blue-1.jpg";
img.onload = function () {
const width = img.width;
const height = img.height;
ctx.drawImage(
img, // Source image
width / 2, // Start at this x of image
height / 2, // Start at this y of image
width / 2, // Till this width of image
height / 2, // Till this height of image
0, // Start at this x of canvas
0, // Start at this y of image
300, // Till this width of canvas
300 // // Till this height of canvas
);
};
<canvas id="canvas"width="800"height="800"></canvas>
You can also use canvas.width and canvas.height in the canvas values used above for a better scaled result.

HTML flexible canvas scale

I am making a website which will load some blueprint images on a canvas.
but the images are vary in height and width.i Would like to make the canvas scaling equal to the uploaded image scale. How do i code to make the canvas width and height changeble respective to uploaded image.
This done in html5
If I understand you correctly, you want to load images with various dimensions. According to the dimension, set the width / height of the canvas and draw the image?
In that case you could add an eventListener to the image. Once it's loaded, get the width and height. Use those to set the dimensions of the canvas. After that, draw the image on the canvas.
var image = new Image();
image.addEventListener('load', function(e) {
var width = image.width;
var height = image.height;
var canvas = document.querySelector('canvas');
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
});
image.src = 'https://upload.wikimedia.org/wikipedia/commons/c/c4/PM5544_with_non-PAL_signals.png';
<canvas></canvas>
Fiddle
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'images/e1.jpg';
canvas.width = imageObj.naturalWidth;
canvas.height = imageObj.naturalHeight;
this also works

How to apply canvas transformation on multiple images

I'm playing with canvas in HTML5 and Javascript and I have a problem:
I'd like to apply transformations used on the current image to multiple images.
What I did:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
//transformation stuff like:
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, -img.width / 2, -img.height / 2, img.width, img.height);
ctx.beginPath();
ctx.lineTo(42, 42);
ctx.stroke();
ctx.lineTo(42, 24);
ctx.stroke();
...
ctx.rotate(Math.PI / 2);
...
};
img.src = //base64Img;
So I will apply a lot of transformations like draw some lines, crop, zoomIn etc...
How can I apply this to multiple files (more than 200) once (when these transformations are done) ?
Obviously, it will be done in multiples functions like a function to rotate, to draw a line etc.
Thank you for your help.
Put your transformations, path drawings & image drawing into a function with arguments that tell the function how each image will be treated:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png";
function start(){
// Note: img coordinates are [centerX,centerY] rather than the usual [left,top]
drawTransformedImage(img,25,50,0,.75);
drawTransformedImage(img,75,50,Math.PI*1/6,1);
drawTransformedImage(img,150,50,Math.PI*2/6,2);
drawTransformedImage(img,225,50,Math.PI*3/6,1);
drawTransformedImage(img,275,50,Math.PI*4/6,.5);
}
function drawTransformedImage(img,cx,cy,radAngle,scale){
// save incoming styling
var lw=ctx.lineWidth;
var ss=ctx.strokeStyle;
// cache often used half-sizes
var iwHalf=img.width/2;
var ihHalf=img.height/2;
ctx.lineWidth=2;
// do the specified transformations
ctx.translate(cx,cy);
ctx.rotate(radAngle);
ctx.scale(scale,scale);
// draw the image
ctx.drawImage(img,-iwHalf,-ihHalf);
// stroke some paths
ctx.beginPath();
ctx.moveTo(-iwHalf,ihHalf);
ctx.lineTo(-iwHalf,-ihHalf);
ctx.strokeStyle='orange';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(-iwHalf,-ihHalf);
ctx.lineTo(+iwHalf,-ihHalf);
ctx.strokeStyle='blue';
ctx.stroke();
// clean up: reset transformations and stylings
ctx.setTransform(1,0,0,1,0,0);
ctx.lineWidth=lw;
ctx.strokeStyle=ss;
}
body{ background-color: white; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=150></canvas>
Transforming an Image
Your example does not show a image being transformed, making your question unclear.
The transform is independent of the image, it is used to transform pixel coordinates drawn onto the canvas. It does not affect the image. You can set the transform and then draw the 200 images and they will all have the same transformation applied when their content is rendered to the canvas.
Code example
To transform the image you must create a canvas, set the transform, then render the image onto that canvas. The canvas is now the transformed image.
An example of transforming an image.
var mirrorImage = function (image, vertical, horizontal) {
var imageResult, ctx, vF, hF, posX, posY;
// create new canvas
imageResult = document.createElement("canvas");
// set the pixels size to match the image
imageResult.width = image.width;
imageResult.height = image.height;
// create a drawable surface
ctx = imageResult.getContext("2d");
// create the mirror transformation
hF = horizontal ? -1, 0;
vF = vertical ? -1 : 0;
posX = horizontal ? image.width, 0;
posY = vertical ? image.height : 0;
// Apply the transform to the new image
ctx.setTransform(hF, 0, 0, vF, posX, posY);
// transform the original image by drawing it onto the new
ctx.drawImage(image, 0, 0);
// return the new image.
return imageResult;
}
// create image
var img = new Image();
img.src = "ship.png";
// when loaded transform the image
img.onload = function () {
img = mirrorImage(img, true, true);
// the image has been transformed.
}
To do that to 200 images you have to call mirrorImage (or what ever you are doing) for each image.

Create Canvas element with image and append to parent

I need to create Canvas element with image and need to append to parent for this i have done this
<html>
<head>
<script>
window.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.id = "canvas_id";
canvas.setAttribute("class" ,"canvas");
canvas.height = "400";
canvas.width = "800";
var image = new Image();
image.src = "http://localhost/tile.png";
image.onload = function(){
context.drawImage(image, canvas.width, canvas.height);
}
document.body.appendChild(canvas);
}
</script>
</head>
<body>
</body>
</html>
it give blank canvas
can somebody guide me ?
You are using drawImage() the wrong way. Instead of drawing the image at (0,0) you are drawing it just outside the canvas area as width and height is where position normally goes.
The valid signatures are:
context.drawImage(image, dx, dy)
context.drawImage(image, dx, dy, dw, dh)
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Where dx and dy are delta position (relative to origin, normally (0,0) when untranslated). Without width and height specified drawImage() will by default use the image's natural width and height.
The second version allows to override the default size, and the third will allow you to draw from one region to another.
Source
Corrected example:
window.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.id = "canvas_id";
canvas.className = "canvas"; // should be className
canvas.height = 400; // should be numbers
canvas.width = 800;
var image = new Image();
image.onload = function() {
// or set canvas size = image, here: (this = currently loaded image)
// canvas.width = this.width;
// canvas.height = this.height;
context.drawImage(this, 0, 0); // draw at (0,0), size = image size
// or, if you want to fill the canvas independent on image size:
// context.drawImage(this, 0, 0, canvas.width, canvas.height);
}
// set src last (recommend to use relative paths where possible)
image.src = "http://lorempixel.com/output/fashion-q-c-800-400-7.jpg";
document.body.appendChild(canvas);
}
That being said, if you only need the image appended there is no need to go via canvas. Just add the image to DOM directly (I assume this is not you want, but just in case..):
var image = new Image();
image.src = "tile.png";
document.body.appendChild(image);
This is my take on it... You need to indicate the coordinates where you want to start drawing (i.e. 0, 0) and - optionally - you can specify how big (wide, height) the canvas is to be.
In my case, I make the canvas to be as big as the image (instead of an arbitrary 400x800) you may need to update that your suit your requirements.
I added some css to show how big the canvas is in relation to the image. You can update/remove that as well depending on your needs.
UPDATED
It uses an hidden image as the source.
I hope this will work for you.
window.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
canvas.id = 'canvas_id';
canvas.setAttribute("class", "canvas");
var image = new Image();
image.src = 'http://placekitten.com/g/200/300';
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
document.body.appendChild(canvas);
}
.canvas {
border: solid red 1px;
}
<html>
<body>
</body>
</html>

Categories