Related
Before I edited my code to create the boxes as objects and push them into an array, I could draw multiple boxes on the canvas and all of them would show up at once (until I cleared the canvas). However, now only one box shows up on the canvas at once, and when I draw another box, the previous box would be removed (although they would still be created as an object and pushed into the array). How do I edit my code so that I can draw multiple boxes onto the canvas and have them all show up together, until I clear the canvas?
Code:
const annotation = {
xcoordi: 0,
ycoordi: 0,
width: 0,
height: 0,
printCoordinates: function () {
console.log(`X: ${this.xcoordi}px, Y: ${this.ycoordi}px, Width: ${this.width}px, Height: ${this.height}px`);
}
};
//the array of all rectangles
let boundingBoxes = [];
// the actual rectangle, the one that is being drawn
let o={};
// a variable to store the mouse position
let m = {},
// a variable to store the point where you begin to draw the rectangle
start = {};
// a boolean
let isDrawing = false;
function handleMouseDown(e) {
start = oMousePos(canvas2, e);
isDrawing = true;
//console.log(start.x, start.y);
canvas2.style.cursor = "crosshair";
}
function handleMouseMove(e) {
if(isDrawing){
m = oMousePos(canvas2, e);
draw();
}
}
function handleMouseUp(e) {
canvas2.style.cursor = "default";
isDrawing = false;
const box = Object.create(annotation);
box.xcoordi = o.x;
box.ycoordi = o.y;
box.width = o.w;
box.height = o.h;
boundingBoxes.push(box);
draw();
box.printCoordinates();
console.log(boundingBoxes)
}
function draw() {
o.x = start.x; // start position of x
o.y = start.y; // start position of y
o.w = m.x - start.x; // width
o.h = m.y - start.y; // height
clearcanvas();
// draw all the rectangles saved in the rectsRy
boundingBoxes.map(r => {drawRect(r)})
// draw the actual rectangle
drawRect(o);
}
canvas2.addEventListener("mousedown", handleMouseDown);
canvas2.addEventListener("mousemove", handleMouseMove);
canvas2.addEventListener("mouseup", handleMouseUp);
function savecanvas(){
context2.clearRect(0, 0, canvas2.width, canvas2.height);
var savedBoxes = boundingBoxes.slice(0);
console.log(savedBoxes); // ok
}
function resetcanvas(){
context2.clearRect(0, 0, canvas2.width, canvas2.height);
boundingBoxes.length = 0;
console.log(boundingBoxes); // ok
}
function drawRect(o){
context2.strokeStyle = "limegreen";
context2.lineWidth = 2;
context2.beginPath(o);
context2.rect(o.x,o.y,o.w,o.h);
context2.stroke();
}
// Function to detect the mouse position
function oMousePos(canvas2, evt) {
let ClientRect = canvas2.getBoundingClientRect();
return {
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
Any help is really appreciated, thank you!
You have 2 errors:
in your code you are using a clearcanvas(); function which is not defined. I've replaced it with context2.clearRect(0, 0, canvas2.width, canvas2.height);
and this is more important: the object you save has these properties: xcoordi, ycoordi, width, height, BUT in drawRect(o) you are using x, y, w, h to draw the rect, but x, y, w, h are undefined, and thus no rect is drawn.
Please check my code:
const canvas2 = document.getElementById("canvas");
const context2 = canvas.getContext("2d");
const annotation = {
x: 0,
y: 0,
w: 0,
h: 0,
printCoordinates: function () {
console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);
}
};
//the array of all rectangles
let boundingBoxes = [];
// the actual rectangle, the one that is being drawn
let o={};
// a variable to store the mouse position
let m = {},
// a variable to store the point where you begin to draw the rectangle
start = {};
// a boolean
let isDrawing = false;
function handleMouseDown(e) {
start = oMousePos(canvas2, e);
isDrawing = true;
//console.log(start.x, start.y);
canvas2.style.cursor = "crosshair";
}
function handleMouseMove(e) {
if(isDrawing){
m = oMousePos(canvas2, e);
draw();
}
}
function handleMouseUp(e) {
canvas2.style.cursor = "default";
isDrawing = false;
const box = Object.create(annotation);
box.x = o.x;
box.y = o.y;
box.w = o.w;
box.h = o.h;
boundingBoxes.push(box);
draw();
box.printCoordinates();
console.log(boundingBoxes)
}
function draw() {
o.x = start.x; // start position of x
o.y = start.y; // start position of y
o.w = m.x - start.x; // width
o.h = m.y - start.y; // height
//clearcanvas();
context2.clearRect(0, 0, canvas2.width, canvas2.height);//////***********
// draw all the rectangles saved in the rectsRy
boundingBoxes.map(r => {drawRect(r)})
// draw the actual rectangle
drawRect(o);
}
canvas2.addEventListener("mousedown", handleMouseDown);
canvas2.addEventListener("mousemove", handleMouseMove);
canvas2.addEventListener("mouseup", handleMouseUp);
function savecanvas(){
context2.clearRect(0, 0, canvas2.width, canvas2.height);
var savedBoxes = boundingBoxes.slice(0);
console.log(savedBoxes); // ok
}
function resetcanvas(){
context2.clearRect(0, 0, canvas2.width, canvas2.height);
boundingBoxes.length = 0;
console.log(boundingBoxes); // ok
}
function drawRect(o){
context2.strokeStyle = "limegreen";
context2.lineWidth = 2;
context2.beginPath(o);
context2.rect(o.x,o.y,o.w,o.h);
context2.stroke();
}
// Function to detect the mouse position
function oMousePos(canvas2, evt) {
let ClientRect = canvas2.getBoundingClientRect();
return {
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
canvas{border:1px solid;}
<canvas id="canvas"></canvas>
void function() {
"use strict";
// Variables
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var rectangles = [];
var isDrawing = false;
var mouseStartX = 0.0;
var mouseStartY = 0.0;
var mouseEndX = 0.0;
var mouseEndY = 0.0;
// Functions
// Constructor function (called with 'new')
function Rectangle(x,y,width,height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
function draw() {
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "limegreen";
ctx.lineWidth = 2;
ctx.beginPath();
for (var i = 0; i < rectangles.length; ++i) {
var rectangle = rectangles[i];
ctx.rect(
rectangle.x,
rectangle.y,
rectangle.width,
rectangle.height
);
}
ctx.stroke();
}
function getMousePosition(e) {
if (canvas && e) {
var bounds = canvas.getBoundingClientRect();
return [
e.clientX - bounds.left,
e.clientY - bounds.top
];
} else {
return [
0.0,
0.0
];
}
}
// Event Handlers
window.onmousedown = function(e) {
if (!isDrawing) {
isDrawing = true;
// Destructuring Assignment
[mouseStartX,mouseStartY] = getMousePosition(e);
canvas.style.cursor = "crosshair";
}
}
window.onmouseup = function(e) {
if (isDrawing) {
isDrawing = false;
// Destructuring Assignment
[mouseEndX,mouseEndY] = getMousePosition(e);
rectangles.push(
new Rectangle(
mouseStartX,
mouseStartY,
mouseEndX - mouseStartX,
mouseEndY - mouseStartY
)
);
draw();
canvas.style.cursor = "default";
}
}
window.onmousemove = function(e) {
if (isDrawing) {
// Destructuring Assignment
[mouseEndX,mouseEndY] = getMousePosition(e);
draw();
ctx.strokeStyle = "darkred";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rect(
mouseStartX,
mouseStartY,
mouseEndX - mouseStartX,
mouseEndY - mouseStartY
);
ctx.stroke();
}
}
// Runs when the page loads
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
draw();
}
}();
canvas {
display: block;
margin: auto;
border: solid 2px black;
border-radius: 10px;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
I have two buttons. The one onClick runs a function that uses a var intId = setInterval{function(), 30}
On the second button i try to stop the setInterval with clearInterval(intId) but intId is not global virable and if i put the whole setInterval outside of the function of the button it can't run.
run button
var intID == 0;
function runButton() {
var c = document.getElementById("can1");
var ctx = c.getContext("2d");
var speed = 2;
var posX = 20;
var posY = 20;
var intID = setInterval(function() {
posX += speed;
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
ctx.fillRect(posX, posY, 20, 20);
if (intID == 1) {
clearInterval(intID);
}
}
, 30);
}
stop button
function stopButton() {
var c = document.getElementById("can1");
var ctx = c.getContext("2d");
clearInterval(intID);
intID == 1;
ctx.clearRect(0, 0, c.width, c.height);
c.style.backgroundColor = red;
}
Try as follows.
var intervalID = 1;
function runButton() {
var c = document.getElementById("can1");
var ctx = c.getContext("2d");
var speed = 2;
var posX = 20;
var posY = 20;
var intID = setInterval(function() {
posX += speed; //variable 'x' had to change to 'posX'
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
ctx.fillRect(posX, posY, 20, 20);
if(intervalID == 0) {
clearInterval(intID);
}
}, 30);
}
function stopButton() {
var c = document.getElementById("can1");
var ctx = c.getContext("2d");
intervalID = 0;
ctx.clearRect(0, 0, c.width, c.height);
c.style.backgroundColor = red;
}
I'm trying to create a hover effect for a canvas image when a mousemove over the image, a transparent overlay shows up. Once a user mouseout am trying to restore the canvas back to it initial stage by making use of the Canvas restore method but it keeps failing. Below is the whole code
var images = [];
var halfCircle;
var ctx;
var canvas;
var effect = true;
jQuery(document).ready(function() {
canvas = document.getElementById("myCanvas");
canvas.style.backgroundColor = '#fafafa';
ctx = canvas.getContext("2d");
halfCircle = new HalfCircle();
halfCircle.doArch(ctx);
placeImages(ctx);
addEventListenersToCanvas(canvas, ctx);
});
function placeImages(ctx){
first_image = new Image();
first_image.src = 'http://example.com/media/features/0.png';
first_image.onload = function(){
ctx.drawImage(first_image, 20, 20);
images.push({x:20,y:20,link: "http://example.com/shoppinglist-infographic", img : first_image});
ctx.save();
}
second_image = new Image();
second_image.src = "http://example.com/media/features/1.png";
second_image.onload = function(){
ctx.drawImage(second_image, 130, 150);
images.push({x:130,y:150,link: "http://example.com/referral/invite?g=banner", img : second_image});
ctx.save();
}
third_image = new Image();
third_image.src = "http://example.com/media/features/2.png";
third_image.onload = function(){
ctx.drawImage(third_image, 230, 220);
images.push({x:230,y:220,link: "http://example.com/all-fast-delivery/", img : third_image});
ctx.save();
}
fourth_image = new Image();
fourth_image.src = "http://example.com/media/features/3.png";
fourth_image.onload = function(){
ctx.drawImage(fourth_image,460, 220);
images.push({x:460,y:220,link:"http://example.com/busyhomemaker/", img : fourth_image});
ctx.save();
}
fifth_image = new Image();
fifth_image.src = "http://example.com/media/features/4.png";
fifth_image.onload = function(){
ctx.drawImage(fifth_image,570, 150);
images.push({x:570,y:150,link:"#", img: fifth_image});
ctx.save();
}
sixth_image = new Image();
sixth_image.src = "http://example.com/media/features/5.png";
sixth_image.onload = function(){
ctx.drawImage(sixth_image,620, 20);
images.push({x:620,y:20,link:"#", img:sixth_image});
ctx.save();
}
text_image = new Image();
text_image.src = "http://example.com/media/features/text.png";
text_image.onload = function(){
ctx.drawImage(text_image,285, 20);
ctx.save();
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function addEventListenersToCanvas(canvas, ctx){
ctx.save();
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
for(var i = 0; i < images.length; i++){
if( (mousePos.x > images[i].x) && (mousePos.x < (images[i].x + images[i].img.width)) &&
(mousePos.y > images[i].y) && (mousePos.y < (images[i].y + images[i].img.height))
){
document.body.style.cursor = "pointer";
if(effect) {
ctx.fillStyle = "#fafafa";
ctx.globalAlpha = 0.1;
ctx.fillRect(images[i].x, images[i].y, images[i].img.width, images[i].img.height);
effect = false;
}
}else{
document.body.style.cursor = "auto";
ctx.restore();
effect = true;
}
}
});
//
canvas.addEventListener('click', function(event){
var mousePos = getMousePos(canvas, event);
for(var i = 0; i < images.length; i++){
if(
(mousePos.x > images[i].x) && (mousePos.x < images[i].x + images[i].img.width) &&
(mousePos.y > images[i].y) && (mousePos.y < images[i].y + images[i].img.height)
){
// console.log('clicking on: ' + images[i].link);
window.open(images[i].link);
}
}
});
}
var HalfCircle = function(){
this.numOfArch = 6;
this.posX = 438;
this.posY = 20;
this.rad = 170;
this.color = [
{ start_color: 'rgb(255,182,54)', end_color: 'rgb(255,220,159)' },
{ start_color: 'rgb(240,97,38)', end_color: 'rgb(249,166,57)' },
{ start_color: 'rgb(254,107,108)', end_color: 'rgb(250,74,78)' },
{ start_color: 'rgb(0,131,195)', end_color: 'rgb(0,150,219)' },
{ start_color: 'rgb(115,174,14)', end_color: 'rgb(214,243,137)' },
{ start_color: 'rgb(133,29,250)', end_color: 'rgb(203,159, 255)' },
];
this.lineWidth = 5;
};
HalfCircle.prototype = {
smallDot: function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 7, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
bigDot : function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 10, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
getEndCord: function(startCord){
return startCord + Math.PI/this.numOfArch;
},
doArch : function (ctx){
var startCord = 0;
for( i = 0; i < this.numOfArch; i++ ){
dotStartX = this.rad * Math.cos(startCord) + this.posX;
dotStartY = this.rad * Math.sin(startCord) + this.posY;
this.smallDot(dotStartX, dotStartY, ctx , this.color[i].start_color);
ctx.lineWidth = this.lineWidth;
ctx.beginPath();
ctx.strokeStyle = this.color[i].start_color;
var endCord = this.getEndCord(startCord);
ctx.arc(this.posX, this.posY, this.rad, startCord, endCord , false);
ctx.stroke();
ctx.closePath();
startCord = endCord;
dotStartX = this.rad * Math.cos(endCord) + this.posX;
dotStartY = this.rad * Math.sin(endCord) + this.posY;
this.bigDot(dotStartX, dotStartY, ctx , this.color[i].end_color);
}
}
}
Am seriously would need someone input on these. Thanks
context.save only saves the context state (stylings, transformations, etc). It does not save anything you have drawn on the canvas. So context.restore will only restore the context state, not the drawings.
To remove something you have previously drawn on the canvas, you must clear the entire canvas and redraw everything that you do want on the canvas.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
//
var halfCircle;
var effect = true;
var overlayIndex=-1;
//
var images = [];
images.push({x:20,y:20, link: "http://example.com/shoppinglist-infographic"});
images.push({x:130,y:150,link: "http://example.com/referral/invite?g=banner"});
images.push({x:230,y:220,link: "http://example.com/all-fast-delivery/"});
images.push({x:460,y:220,link:"http://example.com/busyhomemaker/"});
images.push({x:570,y:150,link:"#"});
images.push({x:620,y:20, link:"#"});
images.push({x:285,y:20, link:"#"});
// Define HalfCircle
var HalfCircle = function(){
this.numOfArch = 6;
this.posX = 438;
this.posY = 20;
this.rad = 170;
this.color = [
{ start_color: 'rgb(255,182,54)', end_color: 'rgb(255,220,159)' },
{ start_color: 'rgb(240,97,38)', end_color: 'rgb(249,166,57)' },
{ start_color: 'rgb(254,107,108)', end_color: 'rgb(250,74,78)' },
{ start_color: 'rgb(0,131,195)', end_color: 'rgb(0,150,219)' },
{ start_color: 'rgb(115,174,14)', end_color: 'rgb(214,243,137)' },
{ start_color: 'rgb(133,29,250)', end_color: 'rgb(203,159, 255)' },
];
this.lineWidth = 5;
};
//
HalfCircle.prototype = {
smallDot: function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 7, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
bigDot : function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 10, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
getEndCord: function(startCord){
return startCord + Math.PI/this.numOfArch;
},
doArch : function (ctx){
var startCord = 0;
for( i = 0; i < this.numOfArch; i++ ){
dotStartX = this.rad * Math.cos(startCord) + this.posX;
dotStartY = this.rad * Math.sin(startCord) + this.posY;
this.smallDot(dotStartX, dotStartY, ctx , this.color[i].start_color);
ctx.lineWidth = this.lineWidth;
ctx.beginPath();
ctx.strokeStyle = this.color[i].start_color;
var endCord = this.getEndCord(startCord);
ctx.arc(this.posX, this.posY, this.rad, startCord, endCord , false);
ctx.stroke();
ctx.closePath();
startCord = endCord;
dotStartX = this.rad * Math.cos(endCord) + this.posX;
dotStartY = this.rad * Math.sin(endCord) + this.posY;
this.bigDot(dotStartX, dotStartY, ctx , this.color[i].end_color);
}
}
}
// preload all images
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push('http://example.com/media/features/0.png');
imageURLs.push('http://example.com/media/features/1.png');
imageURLs.push('http://example.com/media/features/2.png');
imageURLs.push('http://example.com/media/features/3.png');
imageURLs.push('http://example.com/media/features/4.png');
imageURLs.push('http://example.com/media/features/5.png');
imageURLs.push('http://example.com/media/features/text.png');
//
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
startLoadingAllImages(imagesAreNowLoaded);
//
// Create a new Image() for each item in imageURLs[]
// When all images are loaded, run the callback (==imagesAreNowLoaded)
function startLoadingAllImages(callback){
// iterate through the imageURLs array and create new images for each
for (var i=0; i<imageURLs.length; i++) {
// create a new image an push it into the imgs[] array
var img = new Image();
imgs.push(img);
// when this image loads, call this img.onload
img.onload = function(){
// this img loaded, increment the image counter
imagesOK++;
// if we've loaded all images, call the callback
if (imagesOK>=imageURLs.length ) {
callback();
}
};
// notify if there's an error
img.onerror=function(){alert("image load failed");}
// set img properties
img.src = imageURLs[i];
}
}
//
function imagesAreNowLoaded(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
halfCircle = new HalfCircle();
draw();
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}
function draw(){
ctx.fillStyle='#fafafa';
ctx.fillRect(0,0,cw,ch);
halfCircle.doArch(ctx);
for(var i=0;i<imgs.length;i++){
ctx.drawImage(imgs[i], images[i].x,images[i].y);
if(i==overlayIndex){
ctx.fillStyle = "#fafafa";
ctx.globalAlpha = 0.35;
ctx.fillRect( images[i].x, images[i].y, imgs[i].width, imgs[i].height);
ctx.globalAlpha = 1.00;
}
}
}
function handleMouseMove(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
//
overlayIndex=-1;
for(var i=0;i<images.length;i++){
var img=images[i];
var image=imgs[i];
if(
mx>img.x && mx<img.x+image.width &&
my>img.y && my<img.y+image.height
){
overlayIndex=i;
}
}
draw();
}
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>
<canvas id="canvas" width=900 height=500></canvas>
hope it will helps you..
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Test</title>
</head>
<body>
<header> </header>
<nav> </nav>
<section>
<div>
<canvas id="canvas" width="320" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
draw();
}
function draw() {
ctx.fillStyle = '#FA6900';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(0,0,15,150);
ctx.save();
ctx.fillStyle = '#E0E4CD';
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(30,0,30,150);
ctx.save();
ctx.fillStyle = '#A7DBD7';
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 15;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(90,0,45,150);
ctx.save();
ctx.restore();
ctx.beginPath();
ctx.arc(185, 75, 22, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(260, 75, 15, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(305, 75, 8, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
init();
</script>
</section>
<aside> </aside>
<footer> </footer>
</body>
</html>
Hello i need make smooth brush likes this:
I try to create it, i make circle and fill it, but result not successful:
Can be seen circles.. this is not smooth like first example
my example code:
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.05";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=5) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
http://codepen.io/anon/pen/NPjwry
Try with a smaller globalAlpha and decrease the stepping (so you draw more circles)
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.01";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=3) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
Updated codepen: http://codepen.io/gpetrioli/pen/ramqBz
There is more simple solution: just set width of line to 25px
let ctx = this.d.transparentUpdateImage.getContext('2d');
if (!this.lastPos) {
this.lastPos = {x: x, y: y};
return
}
ctx.beginPath();
ctx.moveTo(this.lastPos.x, this.lastPos.y);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = 'red';
ctx.lineWidth = 25;
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
this.lastPos = {x: x, y: y};
Hello everybody I've just trying to understands how this does it work
I have a basic canvas base just in javascript and I would like to move it using touch event
I'm not sure about this but Can I use the drag event ?
Do I need to use a loop function ?
How can I trigger that blue cube ?
I know there are lot of javascript engine in fact i'm using phaser but I would like to undertand this
Thank you
var canvas, cx, width, height;
var cube = {
x: 80,
y: 100,
update: function () {
},
draw: function (ctx) {
ctx.save();
ctx.fillStyle = "blue";
ctx.fillRect(100, 410, 50, 50);
ctx.restore();
}
};
function onpress(e) {
e.preventDefault();
var whichArt = e.target;
var touch = e.touches[0];
var moveOffsetX = whichArt.offsetLeft - touch.pageX;
var moveOffsetY = whichArt.offsetTop - touch.pageY;
whichArt.addEventListener('touchmove', function () {
var positionX = touch.pageX + moveOffsetX;
var positionY = touch.pageY + moveOffsetY;
cube.x = positionX;
cube.y = positionY;
console.log(cube.x);
}, false);
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
document.addEventListener("touchstart", onpress);
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
run();
}
function run() {
var loop = function () {
update();
render();
window.requestAnimationFrame(loop, canvas);
}
window.requestAnimationFrame(loop, canvas);
}
function update() {
}
function render() {
cube.draw(ctx);
}
main();
http://jsfiddle.net/marcogomesr/sxbo3r83/
The canvas is only a passive drawing surface : You have to handle the drag by yourself.
Below a short example :
draggables object have to implement isPointInside, and to be added to the list of draggables object.
I used a dragData object that stores the list of draggables object, the currently dragged object, maybe you'll want to store the start/current point of the drag, and handle a drag-offset so the user holds the object right on the point where he/she started dragging.
http://jsfiddle.net/3ksvn4y0/3/
var canvas, cx, width, height;
var canvasRect;
var cube1, cube2;
var dragData = {
draggables: [],
start: { x: 0, y: 0
},
current: { x: 0, y: 0
},
target: null
};
function Cube(x,y,w,h, color) {
this.x=x; this.y=y; this.w=w; this.h = h;
this.color = color;
}
Cube.prototype = {
update: function () {
},
draw: function (ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
isPointInside: function (x, y) {
return (x >= this.x) && (x < this.x + this.w) && (y > this.y) && (y < this.y + this.h);
}
};
var pointerCoords = {
x: 0,
y: 0,
update: function (e) {
var coords = e.touches ? e.touches[0] : e;
this.x = coords.pageX - canvasRect.left;
this.y = coords.pageY - canvasRect.top;
}
};
function onStart(e) {
e.preventDefault();
pointerCoords.update(e);
// look if we start the touch within a draggable object
var target = null;
for (var i = 0; i < dragData.draggables.length; i++) {
var draggable = dragData.draggables[i];
if (draggable.isPointInside(pointerCoords.x, pointerCoords.y)) {
target = draggable;
break;
}
}
dragData.target = target;
}
function onMove(e) {
pointerCoords.update(e);
var target = dragData.target;
if (!target) return;
target.x = pointerCoords.x;
target.y = pointerCoords.y;
}
function onStop(e) {
pointerCoords.update(e);
e.preventDefault();
if (!dragData.target) return;
onMove(e);
dragData.target = null;
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvasRect = canvas.getBoundingClientRect();
canvas.addEventListener("touchstart", onStart);
canvas.addEventListener('touchmove', onMove);
canvas.addEventListener("touchstop", onStop);
canvas.addEventListener("mousedown", onStart);
canvas.addEventListener('mousemove', onMove);
canvas.addEventListener("mouseup", onStop);
cube1 = new Cube(100, 80, 30, 30, 'blue');
cube2 = new Cube(150, 160, 20, 20, 'red');
dragData.draggables.push(cube1, cube2);
run();
}
function run() {
var loop = function () {
requestAnimationFrame(loop);
update();
render();
}
loop();
}
function update() {
}
function render() {
ctx.clearRect(0, 0, width, height);
cube1.draw(ctx);
cube2.draw(ctx);
}
main();