I am moving an inserted image within a Canvas.
HTML
<div id="left">move left</div>
jQuery:
let MoveLeft=0;
$("#left").on("click", function(){
MoveLeft+=10;
});
In the canvas function
function(){
.....
var LeftPos=100; //default
If(MoveLeft!=0)
LeftPos=LeftPos + MoveLeft;
}
ctx.drawImage(img,0,0,imgW,imgH,LeftPos,0,imgW,imgH);
This works, but the movement takes place in a single jump. How do I translate the image smoothly? Like an animation?
let GlassesUp = 0;
$('.MoveGlasses').on("click", function(event) {
if ($(this).hasClass("MoveGlassesUp")) {
GlassesUp += 10;
}
drawMe();
});
var canvas = document.getElementById('cv');
ctx = canvas.getContext('2d');
// core drawing function
var drawMe = function() {
var ImgGlasses = document.getElementById('glasses');
canvas.width = 400;
canvas.height = 400;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var GUp = 50;
if (GlassesUp != 0) {
GUp = GUp - GlassesUp;
//alert(GUp)
}
ctx.drawImage(ImgGlasses, 0, 0, 250, 250, 50, GUp, 250, 250);
}
drawMe();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="MoveGlasses MoveGlassesUp">Up</div>
<canvas id="cv"></canvas>
<img src="https://image.flaticon.com/icons/svg/126/126514.svg" style="height:60px;width:100px;opacity:0" id="glasses" />
The draw function displaces the image by 0.7 per 100ms. You can adjust these two parameters.
let GlassesUp = 0;
var t;
$('.MoveGlassesUp').on("click", function(event) {
clearInterval(t)
t = setInterval(function() {
GlassesUp += 0.7;
drawMe();
}, 100);
setTimeout("clearInterval(t)", 1000)
});
$('.MoveGlassesDown').on("click", function(event) {
clearInterval(t)
t = setInterval(function() {
GlassesUp -= 0.7;
drawMe();
}, 100);
setTimeout("clearInterval(t)", 1000)
});
var canvas = document.getElementById('cv');
ctx = canvas.getContext('2d');
// core drawing function
var drawMe = function() {
var ImgGlasses = document.getElementById('glasses');
canvas.width = 400;
canvas.height = 400;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var GUp = 50;
if (GlassesUp != 0) {
GUp = GUp - GlassesUp;
//alert(GUp)
}
ctx.drawImage(ImgGlasses, 0, 0, 250, 250, 50, GUp, 250, 250);
}
drawMe();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button class="MoveGlasses MoveGlassesUp">up</button>
<button class="MoveGlasses MoveGlassesDown">down</button>
<hr/>
<canvas id="cv"></canvas>
<img src="https://image.flaticon.com/icons/svg/126/126514.svg" style="height:60px;width:100px;opacity:0" id="glasses" />
Related
var ctx;
function roundedImage() {
var img = new Image();
img.onload = function() {
ctx.beginPath();
ctx.arc(160, 150, 75, 0, Math.PI * 2, true); //draw the circle
ctx.lineWidth = 5;
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.clip();
ctx.closePath();
ctx.drawImage(img, 80, 70, 160, 160);
};
img.src = "xxxxx";
img.crossOrigin = "Anonymous";
}
function fillText(name) {
ctx.fillStyle = 'white';
ctx.font = '40pt Calibri';
ctx.fillText(name, 100, 100);
}
function backImg() {
var background = new Image();
background.src = "xxxxx";
background.onload = function(){
ctx.drawImage(background, 3, 3, canvas.width - 7, canvas.height - 7);
roundedImage()
}
}
function createCanvas(width, height) {
var canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
}
function admire() {
createCanvas(400,625)
backImg()
var original64 = canvas.toDataURL
console.log(original64);
}
window.onload = admire();
Everything is working fine but I am unable to get the base64 code. I am getting this in console "ƒ toDataURL() { [native code] }" How can I get base64 of canvas created.
And I want to show that base64 image in another canvas. How can I do that?
How to draw a line in html 5 canvas?
I achived to draw an rectangle but how to draw a straight line. Here is my code.
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!path.length)
return;
ctx.beginPath();
ctx.moveTo.apply(ctx, path[0]);
for (var i = 1,
len = path.length; i < len; ++i)
ctx.lineTo.apply(ctx, path[i]);
ctx.strokeStyle = '#000';
ctx.stroke();
var start = new Date;
var bounds = contextBoundingBox(ctx);
ms.value = ms.value * 1 + Math.round(((new Date) - start - ms.value) / 4);
ctx.strokeStyle = '#c00';
ctx.strokeRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
This above code is for drawing the rectangle, please modify the code to draw a straight line.
DEMO
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
//add event listner to canvas
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mousemove', mouseMove, false);
canvas.addEventListener('mouseup', mouseUp, false);
var mouseDown = false;
var points = [];
var lines = [];
var linePoint = [];
var stPoint;
var endPoint;
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
function Point(x, y) {
this.x = x;
this.y = y;
}
function lineP(stPoint, endPoint) {
this.stPoint = stPoint;
this.endPoint = endPoint;
}
function mouseDown(e) {
mouseDown = true;
stPoint = new Point(e.layerX, e.layerY); //get start point for line
}
function mouseMove(e) {
if (!mouseDown) return;
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height); //redraw image
drawLines(); //draw previous lines
ctx.beginPath();
ctx.moveTo(stPoint.x, stPoint.y);
ctx.lineTo(e.layerX, e.layerY);
ctx.stroke();
ctx.closePath();
}
function mouseUp(e) {
mouseDown = false;
endPoint = new Point(e.layerX, e.layerY); //get end point
linePoint.push(new lineP(stPoint, endPoint)); //store line points for next draw
console.log(linePoint);
}
//draw all lines from stored point
function drawLines() {
linePoint.forEach(function(item) {
ctx.beginPath();
ctx.moveTo(item['stPoint'].x, item['stPoint'].y);
ctx.lineTo(item['endPoint'].x, item['endPoint'].y);
ctx.stroke();
ctx.closePath();
})
}
canvas {
border: 1px solid #999;
}
<canvas id="canvas" width="300" height="300"></canvas>
On mouse down store start value of line and on mouse up store end point of line. (event.layerX,event.layerY) will give the point cordinate.
The code below should make a canvas appear when I click on "space". Every time I click on "space" then it should delete the old canvas and draw a new one (the position is chosen among 6 different possibilities at each click).
I have a problem with the code because it does not delete the old canvas and keeps on drawing them one on top of the other.
How can I fix the problem?
<html>
<head>
</head>
<link rel="stylesheet" href="cssFiles/blackBackground.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<canvas id="myCanvas" width="1260" height="1000" style="border:1px solid red;"></canvas>
<script>
var circle = [[-350,-300],[-350,0],[-350,300],[350,-300],[350,0],[350,300]];
$(document).ready(function() {
document.addEventListener("keydown", function (e) {
if (e.keyCode === 32) { // space is pressed
var idx_circle = Math.floor(Math.random() * 6)
drawCircle(circle[idx_circle][0],circle[idx_circle][1],2.5,1);
}
});
})
function drawCircle(centerX,centerY, scaleX, scaleY){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var radius = 120;
// save state
context.save();
// translate context
context.translate(canvas.width/2 , canvas.height/2 );
// draw circle which will be stretched into an oval
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
// restore to original state
context.restore();
// apply styling
context.fillStyle = 'white';
context.fill();
context.lineWidth = 20;
context.strokeStyle = 'white';
context.stroke();
}
</script>
</body>
</html>
You'd have to clear the canvas using clearRect method, before drawing the circle ...
context.clearRect(0, 0, canvas.width, canvas.height);
var circle = [
[-350, -300],
[-350, 0],
[-350, 300],
[350, -300],
[350, 0],
[350, 300]
];
document.addEventListener("keydown", function(e) {
if (e.keyCode === 32) { // space is pressed
var idx_circle = Math.floor(Math.random() * 6);
drawCircle(circle[idx_circle][0], circle[idx_circle][1], 2.5, 1);
}
});
function drawCircle(centerX, centerY, scaleX, scaleY) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var radius = 120;
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// save state
context.save();
// translate context
context.translate(canvas.width / 2, canvas.height / 2);
// draw circle which will be stretched into an oval
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
// apply styling
context.fillStyle = 'red';
context.fill();
context.lineWidth = 20;
context.strokeStyle = 'black';
context.stroke();
// restore to original state
context.restore();
}
<canvas id="myCanvas" width="1260" height="1000" style="border:1px solid red;"></canvas>
I have a mixture of static, interactive, and animated objects in my canvas. I can't seem to find a way to clear the draw loop in a global way such that there is no 'smearing' in any of the objects. My code is below. Any help greatly appreciated.
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var mouseX = 300;
var mouseY = 300;
var inc = 0;
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveThing();
drawBezier();
drawCircle();
drawInteractive();
var putPoint = function (e) {
// update mouse
mouseX = e.clientX;
mouseY = e.clientY;
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBezier();
drawCircle();
drawInteractive();
}
canvas.addEventListener("mousemove", putPoint);
function drawBezier() {
for (var i = 0; i < 100; i++) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(200, mouseX, 900, -300, i * 20, 600 + Math.random() * 30);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.closePath();
}
}
function drawCircle() {
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
function drawInteractive() {
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(mouseX, mouseY - 40, 100, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
function moveThing() {
inc++;
// ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(95, 50 + inc, 40, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
requestAnimationFrame(moveThing);
}
</script>
I have refactored your code a little creating a function update which is the main loop of the canvas.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var mouseX = 300;
var mouseY = 300;
var inc = 0;
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
update();
var putPoint = function (e) {
// update mouse
mouseX = e.clientX;
mouseY = e.clientY;
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBezier();
drawCircle();
drawInteractive();
}
canvas.addEventListener("mousemove", putPoint);
function drawBezier() {
for (var i = 0; i < 100; i++) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(200, mouseX, 900, -300, i * 20, 600 + Math.random() * 30);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.closePath();
}
}
function drawCircle() {
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
function drawInteractive() {
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(mouseX, mouseY - 40, 100, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveThing();
drawBezier();
drawCircle();
drawInteractive();
requestAnimationFrame(update);
}
function moveThing() {
inc++;
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(95, 50 + inc, 40, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
<canvas id="myCanvas" />
TL;DR How to make canvas element with images to be overlay of second canvas with image.
I have two canvas elements. First one has image of t-shirt. Second one has images which can be added manually. I want to make second one to be overlay of first canvas.
js:
var canvas = document.getElementById('first');
var context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
var image = new Image();
image.src = 'http://neilhem.github.io/dressfor/images/raw-00.png';
image.onload = function() {
context.save();
context.drawImage(image, 0, 0, canvas.width, canvas.height);
drawCustomLogo(context);
}
function drawCustomLogo(context) {
var layerCanvas = document.getElementById('second');
var layerContext = layerCanvas.getContext('2d');
var image = new Image();
image.src = 'http://neilhem.github.io/dressfor/images/forest/pattern.png';
image.onload = function() {
context.save();
context.drawImage(image, 0, 0, 265, 265);
}
context.globalCompositeOperation = 'overlay';
context.drawImage(layerCanvas, 100, 70);
}
I did some example in http://codepen.io/neilhem/pen/JdGZKx
As you can see overlayed image is lighter, how to make result not so light?
What you want is the source-atop type from the globalCompositeOperation property.
Also, in your code, you never use your second canvas so I removed it
var canvas = document.getElementById('first');
var context = canvas.getContext('2d');
context.fillStyle = 'rgba(0,0,0,0)';
context.fillRect(0, 0, canvas.width, canvas.height);
var image = new Image();
image.src = 'http://neilhem.github.io/dressfor/images/raw-00.png';
image.onload = function() {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
drawCustomLogo(context);
}
function drawCustomLogo(context) {
var image = new Image();
image.src = 'http://neilhem.github.io/dressfor/images/forest/pattern.png';
image.onload = function() {
context.save();
context.globalCompositeOperation = "source-atop";
context.drawImage(this, 0, 0);
}
}
body {
background-color: #000;
}
<canvas id="first" width="547" height="646"></canvas>
Ps : you may also want to change
context.fillStyle = '#FFF'; to context.fillStyle = 'rgba(0,0,0,0)';