How to make this draw zoomable - javascript

This is my javascript and html until now. Please can someone help me find a way to make this rect zoomable on mousewheel
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 50;
var height = 35;
var $width = document.getElementById('width');
var $height = document.getElementById('height')
$width.value = width;
$height.value = height;
$width.addEventListener("keyup", function () {
width = this.value;
draw();
}, false);
$height.addEventListener("keyup", function () {
height = this.value;
draw();
}, false);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(40, 40, width, height);
}

You can use the CSS Transform Property called scale just like that !
var canvas = document.getElementById("canvas");
canvas.addEventListener("dblclick", function(){
this.style.transform="scale(1.5)";
});
var ctx = canvas.getContext("2d");
var width = 50;
var height = 35;
var $width = document.getElementById('width');
var $height = document.getElementById('height');
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(40, 40, width, height);
}
draw();
<canvas id="canvas"></canvas>

Related

trying to add a photo instead of color

(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 || "yel");
// 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = false;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = true;
};
}
var img = document.createElement("img");
img.src= "blm.jpg";
var container = document.getElementById('canvas');
init(container, window.innerWidth, window.innerHeight, 'img');
})();
Hi im trying to make a cover for my canvas instead of just a plain black color on my code. instead i would like my image named "blm.jpg" to replace the plain black. Im not sure how to. Im very new to coding and would really appreciate any help that i can get :) I added the var img = document 5 lines from the bottom and the 4th line from the bottom, im not sure if thats meant to be there either.
thank you for any help in advance :)
Here is a simple example on how to do that, I'm just drawing grids over the background image
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
backgroundImage = document.createElement("img");
backgroundImage.src = "https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png";
function makeLine(start_x, start_y, end_x, end_y) {
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
}
function drawGrid(val, color) {
ctx.beginPath();
ctx.strokeStyle = color;
for(var i = 0; i <= canvas.height; i += val) {
makeLine(0, i, canvas.width, i);
}
for(var j = 0; j <= canvas.width; j += val) {
makeLine(j, 0, j, canvas.height);
}
ctx.stroke();
}
// draw it first to make it the background and only when it loads
backgroundImage.onload = function() {
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
drawGrid(10, "blue");
drawGrid(20, "red");
drawGrid(40, "black");
}
canvas {
border-radius: 3px;
box-shadow: 1px 1px 10px blue;
}
<canvas width="320" height="200">
You may noticed that we need to wait for the image to load for drawing it and draw other stuff, but here is another way by wrapping the whole code into the window.onload method and add our image as an HTML element and hide it of course
window.onload = function() {
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
backgroundImage = document.querySelector("#background-img");
function makeLine(start_x, start_y, end_x, end_y) {
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
}
function drawGrid(val, color) {
ctx.beginPath();
ctx.strokeStyle = color;
for(var i = 0; i <= canvas.height; i += val) {
makeLine(0, i, canvas.width, i);
}
for(var j = 0; j <= canvas.width; j += val) {
makeLine(j, 0, j, canvas.height);
}
ctx.stroke();
}
// no need for the .onload since the code is executing after everything loads
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
drawGrid(10, "blue");
drawGrid(20, "red");
drawGrid(40, "black");
}
canvas {
border-radius: 3px;
box-shadow: 1px 1px 10px blue;
}
.hidden {
display: none;
}
<canvas width="320" height="200"></canvas>
<img id="background-img" class="hidden" src="https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png" alt="nature painting">

Rotate an image on top of another canvas image

Currently, I am making a game and in need of making the image rotate toward the cursor. I am using node but the image is in a js tag in the HTML file that uses ctx to draw the image.
If I put a ctx.rotate(angle); pretty much anywhere it will rotate everything; player, map, etc. I need help so that only the player is rotated
this is a simplified version of my code:
<canvas id="ctx" width="200" height="200"></canvas>
<script>
//game
var ctx = document.getElementById("ctx").getContext("2d");
var WIDTH = 200;
var HEIGHT = 200;
var Img = {};
//player
Img.player = new Image();
Img.player.src = '/client/img/player.png';
var Player = function(/*node*/){
ctx.drawImage(Img.player, ...);
}
//map
Img.map = new Image();
Img.map.src = '/client/img/map.png';
//display everything
setInterval(function(){
ctx.clearRect(0,0,200,200);
drawMap();
for(var i in Player.list)
Player.list[i].draw();
},1000/60);
//functions
//move map so that player is always in the middle
var drawMap= function(){
var x = WIDTH/2 - Player.list[/*node*/].x;
var y = HEIGHT/2 - Player.list[/*node*/].y;
ctx.drawImage(Img.map,x,y);
}
</script>
Here's an example of what you may be looking for
const ctx = document.getElementById("ctx").getContext("2d");
const WIDTH = 500,
HEIGHT = 500;
document.getElementById("ctx").height = HEIGHT;
document.getElementById("ctx").width = WIDTH;
var Player = {
x: 50,
y: 55,
angle: 0
}
document.addEventListener("mousemove", (event) => {
var x = event.clientX - Player.x,
y = event.clientY- Player.y,
angle = Math.atan2(y,x);
Player.angle = angle
})
function draw() {
window.requestAnimationFrame(draw);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.translate(Player.x, Player.y);
ctx.rotate(Player.angle);
ctx.translate(-Player.x, -Player.y);
ctx.fillRect(Player.x, Player.y, 20, 20);
ctx.restore();
ctx.fillRect(150, 50, 20, 20);
}
draw();
<canvas id="ctx"></canvas>
jsfiddle here
Hope this helps!

How to scale an image for a canvas pattern?

I want to fill a Canvas with an Image and scale it to a certain width beforehand.
I am trying to achieve an effect where an image in the foreground of the canvas can be erased with the mouse to view an image in the background. This is why I need to use a pattern to fill my canvas instead of just using drawImage(). Everything works apart from the scaling of the foreground image. Here is my code for generating the pattern:
var blueprint_background = new Image();
blueprint_background.src = "myfunurl";
blueprint_background.width = window.innerWidth;
blueprint_background.onload = function(){
var pattern = context.createPattern(this, "no-repeat");
context.fillStyle = pattern;
context.fillRect(0, 0, window.innerWidth, 768);
context.fill();
};
This does exactly what it should do, except that the image keeps its original size.
As you see, I want the image to scale to window.innerWidth (which has the value 1920 when logging it).
If needed, I can provide the rest of the code, but since the error is most likely in this snippet, I decided not to post the rest.
EDIT: Here is my full code with the suggested changes. The front ground image now displays over the full width, however the erasing does not work anymore.
JavaScript (Note that I use jQuery instead of $):
jQuery(document).ready(function() {
var cwidth = window.innerWidth;
var cheight = 768;
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(canvas, fillColor) {
var ctx = canvas.context;
canvas.isDrawing = true;
jQuery('#canvas').children().css('position:absolute; top: ' + jQuery('#Top_bar').height() + 'px');
// 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();
};
// bind mouse events
canvas.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - jQuery('#Top_bar').outerHeight();
var radius = 30;
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
}
var container = document.getElementById('canvas');
jQuery('#canvas').css('position:absolute; top: ' + jQuery('#Top_bar').height() + 'px');
var canvas = createCanvas(container, cwidth, cheight);
init(canvas, '#ddd');
var fgimg = document.getElementById("fgimg");
fgimg.width = cwidth;
var context = canvas.node.getContext("2d");
let canvasP = document.getElementById("pattern");
canvasP.width = window.innerWidth;
canvasP.height = 768;
let ctxP = canvasP.getContext("2d");
ctxP.drawImage( fgimg, 0, 0,window.innerWidth,768 );
context.fillStyle = context.createPattern(canvasP,"no-repeat");
context.fillRect(0,0, canvas.width, canvas.height);
});
CSS:
#canvas {
background:url(http://ulmke-web.de/wp-content/uploads/2019/01/Header-6.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
width: 100%;
height: 768px;
}
HTML:
<div id="canvas">
<canvas id="pattern">
</div>
<div style="display:none">
<img id="fgimg" src=" http://ulmke-web.de/wp-content/uploads/2019/01/Header-5.jpg">
</div>
I would use two canvases. On the first one you draw your image and you use this canvas as an image to create the pattern. In order to scale the image you scale the size of the first canvas #pattern in my example.
For example you can do this for a 10/10 image:
canvasP.width = 10;
canvasP.height = 10;
ctxP.drawImage( redpoint, 2.5, 2.5 );
or you can do this for a 20/20 image:
canvasP.width = 20;
canvasP.height = 20;
ctxP.drawImage( redpoint, 5, 5,10,10 );
Furthermore, in my example I'm adding a little margin around the image.
let canvasP = document.getElementById("pattern");
if (canvasP && canvasP.getContext) {
let ctxP = canvasP.getContext("2d");
/*canvasP.width = 10;
canvasP.height = 10;
ctxP.drawImage( redpoint, 2.5, 2.5 ); */
canvasP.width = 20;
canvasP.height = 20;
ctxP.drawImage( redpoint, 5, 5,10,10 );
}
let canvas1 = document.getElementById("canvas");
if (canvas1 && canvas1.getContext) {
let ctx1 = canvas1.getContext("2d");
if (ctx1) {
ctx1.fillStyle = ctx1.createPattern(canvasP,"repeat");
ctx1.fillRect(0,0, canvas1.width, canvas1.height);
}
}
canvas{border:1px solid}
<img id="redpoint" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==">
<canvas id="pattern"></canvas>
<canvas id="canvas"></canvas>
I hope it helps.

Canvas background hide the rects that I added

I am new here, so please be consider.
I've created a new canvas and created a rects in the canvas , when I set a background to the canvas I have a terrible problem that The background is on the shapes
Here is the code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var background = new Image();
background.src = "url_to_image";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
<canvas id="canvas" width=450 height=700></canvas>
Thanks
Edit:
I found in my code a function of fillStyle that change my background,
so I delete it and instead of this I put this:
var w = canvas.width;
var h = canvas.height
var img = new Image();
img.src = "http://www.girija.info/wp-content/uploads/2015/08/Paznja-Sabranost-450x700.png";
img.onload = function () {
var pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, w, h);
};
//ctx.fillStyle = "#FAF7F8";
rect(0, 0, WIDTH, HEIGHT);
// redraw each rect in the rects[] array
for (var i = 0; i < rects.length; i++) {
var r = rects[i];
ctx.fillStyle = 'red';
rect(r.x, r.y, r.width, r.height);
}
But every drag of the rect (the rects loaded from stack and can be draggable) the background color of the rect change
You can set the background using the css property
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
ctx.rect(10, 10, 100, 100);
ctx.fill();
canvas.style.backgroundImage = 'url(https://picsum.photos/450/700)';
<canvas id="canvas" width=450 height=700></canvas>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
background_image();
function background_image()
{
background_image = new Image();
background_image.src = 'https://image.ibb.co/kmV8kz/photodune_2359510_smiles_l_22.png';
background_image.onload = function(){
context.drawImage(background_image, 0, 0);
}
}
<canvas id="canvas" width=450 height=700></canvas>

HTML5 Canvas scaling an image animation

I've created a straight forward linear HTML5 animation but I now want the image to continuously scale bigger then smaller until the end of the canvas' height.
What's the best way to do this?
Here's a JSFIDDLE
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame;
var canvas = document.getElementById('monopoly-piece');
var context = canvas.getContext('2d');
var img = document.createElement("img");
img.src = "images/tophat.png";
img.shadowBlur = 15;
img.shadowColor = "rgb(0, 0, 0)";
var xSpeed = 0; //px per ms
var ySpeed = 0.15;
function animate(nowTime, lastTime, xPos, yPos) {
// update
if ((img.style.height + yPos) > canvas.height) {
xPos = 0;
yPos = 0;
}
var timeDelta = nowTime - lastTime;
var xDelta = xSpeed * timeDelta;
var yDelta = ySpeed * timeDelta;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// shadow
context.shadowOffsetX = 3;
context.shadowOffsetY = 7;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
//draw img
context.drawImage(img, xPos, yPos);
if (yPos > canvas.height - img.height ) {
addMarker();
}
else {
requestAnimationFrame(
function(timestamp){
animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta);
}
);
}
}
animate(0, 0, -10, 0);
Here is my current code which animates an image from the top of the canvas element to the bottom and then stops.
Thanks.
context.DrawImage has additional parameters that let you scale your image to your needs:
// var scale is the scaling factor to apply between 0.00 and 1.00
// scale=0.50 will draw the image half-sized
var scale=0.50;
// var y is the top position on the canvas where you want to drawImage your image
var y=0;
context.drawImage(
// draw img
img,
// clip a rectangular portion from img
// starting at [top,left]=[0,0]
// and with width,height == img.width,img.height
0, 0, img.width, img.height,
// draw that clipped portion of of img on the canvas
// at [top,left]=[0,y]
// with width scaled to img.width*scale
// and height scaled to img.height*scale
0, y, img.width*scale, img.height*scale
)
Here's an example you can start with and fit to your own design needs:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var scale = 1;
var scaleDirection = 1
var iw, ih;
var y = 1;
var yIncrement = ch / 200;
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start() {
iw = img.width;
ih = img.height;
requestAnimationFrame(animate);
}
function animate(time) {
if (scale > 0) {
requestAnimationFrame(animate);
}
ctx.clearRect(0, 0, cw, ch);
ctx.drawImage(img, 0, 0, iw, ih, 0, y, iw * scale / 100, ih * scale / 100);
scale += scaleDirection;
if (scale > 100) {
scale = 100;
scaleDirection *= -1;
}
y += yIncrement;
}
$("#test").click(function() {
scale = y = scaleDirection = 1;
requestAnimationFrame(animate);
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="test">Animate Again</button>
<br>
<canvas id="canvas" width=80 height=250></canvas>

Categories