I want to resize the canvas field like paint app in javascript how can I do ?
My html file is :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="paint.css">
<title>Paint</title>
</head>
<body>
<canvas id="canvas" style="border: solid 1px black">Your Browser does not support Canvas, please upgrade</canvas>
<script src="paint.js"></script>
</body>
</html>
Thanks !
It turned out to be a bit more complex.
Resizing the canvas clears it, therefore you need to do it this way:
create a new canvas
assign the dimensions
draw the old canvas over the new canvas
replace the old canvas with the new canvas
//Base canvas and dimensions
var canvas = document.body.appendChild(document.createElement("canvas"));
var width = canvas.height = canvas.width = 400;
var height = width;
var ctx = canvas.getContext("2d");
//Drawing variables
var lastPosition = null;
var drawing = false;
//Drawing functionality
function startDraw() {
drawing = true;
}
canvas.onmousedown = startDraw;
function stopDraw() {
drawing = false;
}
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
function mouseMove(evt) {
var pos = {
x: evt.offsetX,
y: evt.offsetY
};
if (lastPosition !== null && drawing === true) {
ctx.beginPath();
ctx.moveTo(lastPosition.x, lastPosition.y);
ctx.lineTo(pos.x, pos.y);
ctx.closePath();
ctx.stroke();
}
lastPosition = pos;
}
canvas.onmousemove = mouseMove;
//Resizer functions
var resizerX = document.body.appendChild(document.createElement("button"));
resizerX.innerHTML = "Resize X";
resizerX.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new width", width.toString()));
}
var c = document.createElement("canvas");
width = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
var resizerY = document.body.appendChild(document.createElement("button"));
resizerY.innerHTML = "Resize Y";
resizerY.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new height", height.toString()));
}
var c = document.createElement("canvas");
height = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
canvas {
background-color: #eee
}
Related
I'm trying to have an image on my website become saturated at the same location the mouse is. When the mouse moves the saturation effect goes with it, and the area previously hovered over becomes grayscale again. I'm thinking this effect could be accomplished using saturate(), however I haven't had any success with it. Additionally, I would like the effect to be circular without hard edges similar to this.
Example of what it would look like (orange arrow indicating where the mouse is).
Any help or insight would be appreciated, thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content= "width=device-width, initial-scale=1.0" />
</head>
<script>
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
</script>
<canvas></canvas>
</html>
Using a canvas we can try. Here's a start inspired by How can I adjust the huse, saturation, and lightness of in image in HTML5 Canvas?.
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
<canvas></canvas>
This is a simple answer (change the logic of the program as you want):
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 200px;
height: 150px;
}
.image {
width: 100%;
height: 100%;
}
</style>
<script>
const width = 50;
const height = 50;
function create() {
const element = document.createElement("div");
element.id = "filtered";
element.style.width = `${width}px`;
element.style.height = `${height}px`;
element.style.borderRadius = "50%";
element.style.position = "absolute";
element.style.backgroundColor = "red";
element.style.opacity = "0.2";
element.style.zIndex = "2";
return element;
}
function changePos(e) {
x = e.clientX;
y = e.clientY;
let element = document.getElementById("filtered");
if (!element) {
element = create();
document.getElementById("focusArea").appendChild(element);
}
element.style.left = `${x - width / 2}px`;
element.style.top = `${y - height / 2}px`;
}
function removeElement() {
if (document.getElementById("filtered")) {
document.getElementById("filtered").remove();
}
}
</script>
</head>
<body>
<div
id="focusArea"
onmouseleave="removeElement()"
onmousemove="changePos(event)"
class="relative"
>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"
class="image"
/>
</div>
</body>
</html>
I am attempting to locate the coordinates of the mouse on a canvas element of an HTML5 page.
I create the canvas to be a certain height and width, for example 700x700. When I mouse over the canvas, I want to be able to know the X,Y of the mouse. This works fine, until I stretch my canvas using CSS in the HTML file...
Here is my javascript file:
function Sprite(path)
{
this.img = new Image();
this.img.onload = loaded;
this.img.src = path;
function loaded()
{
console.log("Loaded picture");
}
}
function drawSprite(sprite, ctx)
{
console.log("drawing picture");
ctx.drawImage(sprite.img,10,10);
}
//------------------------------------------
function Game()
{
this.canvas = document.createElement("canvas");
document.body.appendChild(this.canvas);
this.canvas.width = 700;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
var ctx = this.context;
ctx.canvas.addEventListener('mousemove', function(event){
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById("coords");
status.innerHTML = mouseX+" | "+mouseY;
});
this.objects = new Array();
this.objects.push(new Sprite("dog.png"));
}
function drawGame(g)
{
console.log("I'm here");
for(var i=0;i<g.objects.length;i++)
{
drawSprite(g.objects[i], g.context);
}
}
function drawLine(g)
{
g.context.moveTo(0,0);
g.context.lineTo(100,100);
g.context.stroke();
}
//------------------
window.addEventListener('load',function(event){startgame();});
var globalGame;
function startgame()
{
globalGame = new Game();
drawGame(globalGame);
drawLine(globalGame);
}
Here is my HTML File
<html>
<head>
<script src="functions.js"></script>
<style>
canvas
{
width:90%;
height:90%;
}
</style>
</head>
<body>
<h1 id="coords">0 | 0</h1>
</body>
<html>
The mouse coordinates are in display pixels. To convert that to canvas coordinates, you'll need to scale them accordingly.
One way of doing this is:
const canvasX = mouseX * canvas.width / canvas.clientWidth;
const canvasY = mouseY * canvas.height / canvas.clientHeight;
as shown in this example:
const status = document.getElementById("coords");
const canvas = document.createElement("canvas");
canvas.width = 700;
canvas.height = 700;
document.body.appendChild(canvas);
canvas.addEventListener('mousemove', event => {
const mouseX = event.clientX - canvas.offsetLeft;
const mouseY = event.clientY - canvas.offsetTop;
// scale mouse coordinates to canvas coordinates
const canvasX = mouseX * canvas.width / canvas.clientWidth;
const canvasY = mouseY * canvas.height / canvas.clientHeight;
status.innerHTML = `${mouseX} | ${mouseY}<br>${canvasX} | ${canvasY}`;
});
canvas {
width:250px;
height:250px;
background-color:#f0f;
}
<div id="coords">??? | ???<br>??? | ???</div>
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>
I have a canvas code to draw a signature. The code works perfectly fine with chrome and Firefox but does not draw at all on IE 11.
My canvas is:
<canvas id="signitureCanvas" style="border: 3px solid #000; cursor:crosshair; background-color:white;"></canvas>
My code is as below:
var canvas = document.getElementById('signitureCanvas');
var ctx = canvas.getContext('2d');
var canvasWidth = 200;
var canvasLength = 120;
canvas.width = canvasWidth;
canvas.height = canvasLength;
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
var tooltype = 'draw';
//Mousedown
$(canvas).on('mousedown', function (e) {
last_mousex = mousex = parseInt(e.clientX - canvasx);
last_mousey = mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function (e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function (e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
ctx.beginPath();
if (tooltype == 'draw') {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 10;
}
ctx.moveTo(last_mousex, last_mousey);
ctx.lineTo(mousex, mousey);
ctx.lineJoin = ctx.lineCap = 'round';
ctx.stroke();
}
last_mousex = mousex;
last_mousey = mousey;
});
function ClearCanvas() {
var canvas = document.getElementById('signitureCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
Is IE 11 in particular having problems?
Edit:
I figured out the problem is with my Iframe:
When height and width are set to 300 everything works fine:
<embed id="fred" type="application/pdf" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="#Model.FilePath" frameborder="1" scrolling="yes" height="300" width="300" />
When I set it to 1000, it won't work:
<embed id="fred" type="application/pdf" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="#Model.FilePath" frameborder="1" scrolling="yes" height="1000" width="1000" />
I believe it's something with the offset but I can't figure how to fix it.
any help?
For further knowledge to whom might ask:
I have found this piece of code that works on all browsers, layerX and layerY are different for firefox browsers:
var canvas = document.getElementById('signitureCanvas');
var ctx = canvas.getContext('2d');
var canvasWidth = 200;
var canvasLength = 120;
canvas.width = canvasWidth;
canvas.height = canvasLength;
var x = 0;
var y = 0;
function tool_pencil() {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button
// This starts the pencil drawing
this.mousedown = function (ev) {
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(x, y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button)
this.mousemove = function (ev) {
if (tool.started) {
ctx.lineTo(x, y);
ctx.stroke();
}
};
// This is called when you release the mouse button
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
}
};
}
// The general-purpose event handler. This function just determines
// the mouse position relative to the <canvas> element
function ev_canvas(ev) {
// Firefox
if (ev.offsetX || ev.offsetX == 0) {
x = ev.offsetX;
y = ev.offsetY;
// Opera
} else if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerX;
}
// Call the event handler of the tool
var func = tool[ev.type];
if (func) {
func(ev);
}
}
function ClearCanvas() {
var canvas = document.getElementById('signitureCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
I am actually trying to implement the functionality where I can add multiple images onto a canvas using array and kineticJs. I am unable to load images onto the canvas however these images are created outside the canvas body. I want to draw these circle images onto the canvas body. Cheers
<html>
<head>
<title>Bomb Game</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src = "https://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.3.min.js"></script>
</head>
<body>
<div id = "container"></div>
<script>
window.onload = $(document).ready(function()
{
var bombLeft, bombTop, bombRight, bombBottom;
var timerLeft, timerTop, timerRight, timerBottom;
var numberCircles = [];
function loadImages(sources, callback)
{
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources)
{
numImages++;
}
for(var src in sources)
{
images[src] = new Image();
images[src].onload = function()
{
if(++loadedImages >= numImages)
{
callback(images);
}
};
images[src].src = sources[src];
}
}
var newCanvas = document.createElement("canvas");
var ctx = newCanvas.getContext("2d");
newCanvas.width = window.innerWidth;
newCanvas.height = window.innerHeight;
newCanvas.style.border = "10px solid #000000";
newCanvas.style.margin = "0px";
$("#container").append(newCanvas);
var sources = {background: 'bomb_artwork/background.jpg', bomb: 'bomb_artwork/bomb.png', timer: 'bomb_artwork/timer.png',
boxSmall: 'bomb_artwork/box_1.png',boxBig: 'bomb_artwork/box_2.png', numberCircle: 'bomb_artwork/number_circle.png', explode: 'bomb_artwork/explode.png'};
function initStage(images)
{
var stage = new Kinetic.Stage({
container: 'container',
width: newCanvas.width,
height: newCanvas.height
});
var layer = new Kinetic.Layer();
loadImages(sources,function(images){
<!-- For background image -->
ctx.drawImage(images.background,0,0,newCanvas.width,newCanvas.height);
x1 = newCanvas.width/7;
y1 = newCanvas.height/3;
x2 = newCanvas.width/8;
y2 = newCanvas.height/8;
<!-- To add boxes in background>
ctx.drawImage(images.boxBig,750,370,150,120);
ctx.drawImage(images.boxBig,754,270,150,120);
ctx.drawImage(images.boxSmall,788,210,120,80);
<!-- For bombbottom -->
bombBottom = images.bomb;
timerBottom = images.timer;
ctx.drawImage(bombBottom,newCanvas.width/2-newCanvas.width/8,newCanvas.height-150,x1,y1);
ctx.drawImage(timerBottom,newCanvas.width/2+newCanvas.width/10000,newCanvas.height-50,x2,y2);
ctx.font = "28pt Times New Roman";
ctx.fillStyle = "yellow";
ctx.fillText("Player 1", 720, 635);
ctx.font = "20pt Times New Roman";
ctx.fillStyle = "yellow";
ctx.fillText("? - 6 = 11", 730, 670);
<!-- For bombleft-->
bombLeft = images.bomb;
timerLeft = images.timer;
ctx.save();
ctx.rotate(Math.PI / 2);
ctx.drawImage(bombLeft,230,-newCanvas.height/4,x1,y1);
ctx.drawImage(timerLeft,400,-newCanvas.height/13,x2,y2);
ctx.restore();
<!-- For bombtop-->
bombTop = images.bomb;
timerTop = images.timer;
ctx.save();
ctx.translate(100, 100);
ctx.rotate(Math.PI);
ctx.drawImage(bombTop,-650,-50,x1,y1);
ctx.drawImage(timerTop,-480,50,x2,y2);
ctx.restore();
<!-- For bombright-->
bombRight = images.bomb;
timerRight = images.timer;
ctx.save();
ctx.translate(100, 100);
ctx.rotate(-Math.PI/2);
ctx.drawImage(bombRight,-325,1100,x1,y1);
ctx.drawImage(timerRight,-150,1215,x2,y2);
ctx.restore();
<!-- TO draw random circles -->
for(var i = 0; i < 30;i++)
{
numberCircles[i] = new Kinetic.Image({
image : images.numberCircle,
x : Math.floor(Math.random()* newCanvas.width),
y : Math.floor(Math.random()*newCanvas.height),
width : 50,
height : 50,
draggable : true,
stroke : 'red',
strokeWidth : 10,
strokeEnabled : false
/*if((x > newCanvas.width/8 && x < newCanvas.width-newCanvas.width/6)&&(y > newCanvas.height/4 && y < newCanvas.height-newCanvas.height/3))
{
ctx.drawImage(numberCircles[i],x,y,50,50);
}
else
{
i = i-1;
continue;
}*/
});
layer.add(numberCircles[i]);
stage.add(layer);
}
// use event delegation to update pointer style
// and apply borders
layer.on('mouseover', function(evt) {
//var shape = evt.shape;
document.body.style.cursor = 'pointer';
//shape.enableStroke();
layer.draw();
});
layer.on('mouseout', function(evt) {
//var shape = evt.shape;
document.body.style.cursor = 'default';
//shape.disableStroke();
layer.draw();
});
});
}
loadImages(sources,initStage);
});
</script>
</body>
</html>