Hello all can we place drag and drop functionality inside canvas using html5??
My actual requirement is to drag the image into textbox that should be done inside the canvas...
please share your ideas..The following link i used to learn drag and drop but it should be done inside the canvas..
http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_draganddrop
You can learn more in this tutorial: http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/
From your limited description in your question, it sounds like you drag items over the canvas and this tutorial is likely the best match.
This is the actual code you can paste into file and open in HTML5 compliant browser and it will work:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Drag and Drop Test</title>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="400" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var x = 75;
var y = 50;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#444444";
rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
</script>
</section>
</body>
</html>
Related
I'm trying to draw squares at the corners of a canvas. The top ones work but I should be able to draw the third square which I have partially drawn.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="application/javascript">
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var t = getRandomInt(10);
function draw() {
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var t = getRandomInt(10);
const canvas = document.getElementById('canvas');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
setInterval(myTimer, t*100);
function myTimer() {
var i = 0;
var x = window.innerWidth;
var y = window.innerHeight;
y = y + 100;
//draw crosshair
console.log("x = "+ x);
console.log("y = "+ y);
console.log("i = "+ i);
ctx.beginPath();
var crosshairlength = 20;
var lengthxminus = crosshairlength;
var lengthxplus = crosshairlength;
var lengthyminus = crosshairlength;
var lengthyplus = crosshairlength;
//horizontal line
ctx.moveTo((x/2)-lengthxminus, y/2);
ctx.lineTo((x/2)+lengthxplus, y/2);
//vertical line
ctx.moveTo(x/2, (y/2)-lengthyminus);
ctx.lineTo(x/2, (y/2)+lengthyplus);
var t = 10;
//top left
ctx.moveTo(0,0);
ctx.lineTo(t,0);
ctx.lineTo(t,t);
ctx.lineTo(0,t);
ctx.lineTo(0,0);
//top right
ctx.moveTo(x-t,0);
ctx.lineTo(x,0);
ctx.lineTo(x,t);
ctx.lineTo(x-t,t);
ctx.lineTo(x-t,0);
//bottom right
ctx.moveTo(x-t,y-t);
ctx.lineTo(x,y-t);
ctx.lineTo(x,y);
//bottom left
ctx.stroke();
}
i++;
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="1846" height="768"></canvas>
</body>
</html>
Either the canvas is the not the size of the viewport or I am misunderstanding the coordinate system which I believe has the positive y-axis going down and the origin is in the top left.
window.innerWidth and window.innerHeight represent the width and height of the viewport. Your <canvas> width and height are set by its width and height attributes.
If you want the canvas to be the size of the viewport, change these attributes, though changing these attributes come with great side-effects like reassigning a new pixel buffer, and clearing all the properties of the attached context, so it's better to do so only when really needed:
if (canvas.width !== x) {
canvas.width = x;
}
if (canvas.height !== y) {
canvas.height = y;
}
And if you wanted to use the size of the canvas rather than the one of the viewport, then you want
function myTimer() {
var i = 0;
var x = canvas.width;
var y = canvas.height;
I want to drag & drop text above image. For that I am using canvas. I am using this code
<img id="scream" src="http://127.0.0.1/demo/images.jpg" alt="The Scream" style="display:none;" width="220" height="277"><p>Canvas:</p>
<canvas id="canvas" width="300" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
var c=document.getElementById("canvas");
var ctx1=c.getContext("2d");
var img=document.getElementById("scream");
ctx1.drawImage(img,10,10);
var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false,
text = "Hey there im moving!",
textLength = (text.length * 14)/2;
function rect(x,y,w,h) {
ctx.font = "14px Arial";
ctx.strokeText("Hey there im a moving!!", x, y);
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
ctx.fillStyle = "#444444";
rect(x - 15, y + 15, textLength, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + textLength + canvas.offsetLeft && e.pageX > x - textLength + canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
I either able to show image or drag & drop text but I want both, please help me where I am wrong. You can check here:- http://jsfiddle.net/FWdSv/11/
When you're clearing the canvas, you're also clearing your image.
So the easy fix is to redraw the image in your draw function:
function draw() {
clear();
ctx.drawImage(img,0,0);
ctx.fillStyle = "#FAF7F8";
ctx.fillStyle = "#444444";
rect(x - 15, y + 15, textLength, 30);
}
Alternatively:
You could display your image underneath your canvas so it's not affected when you clear the canvas.
I am using Firefox 19.0.2 on Ubuntu Linux.
I'm learning HTML5 but find that the following code's image
flashes repeatedly. Furthermore, I would like for the image
to finish downloading before the script stars:
<!DOCTYPE html>
<html lang="en">
<head>
<meta encoding="UTF-8" />
<title>Hello Canvas</title>
<script type="text/javascript">
window.onload = drawCanvas;
function canvasSupportEnabled() {
return !!document.createElement('canvas').getContext;
}
var Debugger = function() { };
Debugger.log = function(message) {
try {
console.log(message);
} catch (exception) {
return;
}
}
var x = 0;
var y = 0;
function drawCanvas() {
if (!canvasSupportEnabled())
return;
var theCanvas = document.getElementById("myCanvas");
var context = theCanvas.getContext("2d");
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
context.fillStyle = "#000000";
context.font = "20px Sans-Serif";
context.textBaseLine = "top";
context.fillText("Hello World!", 195, 80);
context.strokeStyle = "#000000";
context.strokeRect(x, y, 490, 290);
var platypus = new Image();
platypus.onload = function() {
context.drawImage(platypus, x, y);
}
platypus.src = "http://www.wildwatch.com.au/uploads/Platypus/PLATYPUSweb1.jpg"
window.setTimeout(drawCanvas, 200);
x = x + 5;
y = y + 5;
}
</script>
</head>
<body>
<h1>Hello Canvas.</h1>
<canvas id="myCanvas" width="500" height="300">Your browser does not support HTML5 canvas.</c
</body>
</html>
How can I solve these two problems. Do I need to double-buffer and how can I do it?
How do I detect an onload event for the images to finish being downloaded?
Thanks.
This will load the image first then create and draw the canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta encoding="UTF-8" />
<title>Hello Canvas</title>
<script type="text/javascript">
window.onload = drawCanvas;
function canvasSupportEnabled() {
return !!document.createElement('canvas').getContext;
}
var x = 0;
var y = 0;
function drawCanvas() {
if (!canvasSupportEnabled())
return;
var platypus = new Image();
platypus.onload = function () {
var theCanvas = document.getElementById("myCanvas");
var context = theCanvas.getContext("2d");
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
context.fillStyle = "#000000";
context.font = "20px Sans-Serif";
context.textBaseLine = "top";
context.fillText("Hello World!", 195, 80);
context.strokeStyle = "#000000";
context.strokeRect(x, y, 490, 290);
context.drawImage(this, x, y);
}
platypus.src = "http://www.wildwatch.com.au/uploads/Platypus/PLATYPUSweb1.jpg"
}
</script>
</head>
<body>
<h1>Hello Canvas.</h1>
<canvas id="myCanvas" width="500" height="300">Your browser does not support HTML5 canvas.</canvas>
</body>
</html>
I suspect the issue is the setTimeout call. The first run of the drawCanvas function causes the image to start loading. Once the image is loaded, it'll draw on the canvas, but the subsequent drawCanvas calls caused by the timeout will cause the whole canvas to get filled with the rect you're drawing and thus making the image disappear.
The onload callback will not fire again due to the image already having been loaded.
The simplest way to fix it would be to use a preloader for the images. Basically instead of using your current window.onload handler, use another function which loads your images and stores them in some variables. Once it has finished loading the images, have it call drawCanvas which you would modify to use one of the stored images instead.
The following did it for me.
<!DOCTYPE html>
<html lang="en">
<head>
<meta encoding="UTF-8" />
<title>Hello Canvas</title>
<script type="text/javascript">
window.onload = drawCanvas;
function canvasSupportEnabled() {
return !!document.createElement('canvas').getContext;
}
var x = 0;
var y = 0;
function drawCanvas() {
if (!canvasSupportEnabled())
return;
var platypus = new Image();
platypus.onload = function () {
var theCanvas = document.getElementById("myCanvas");
var context = theCanvas.getContext("2d");
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
context.fillStyle = "#000000";
context.font = "20px Sans-Serif";
context.textBaseLine = "top";
context.fillText("Hello World!", 195, 80);
context.strokeStyle = "#000000";
context.strokeRect(x, y, 490, 290);
context.drawImage(this, x, y);
}
x = x + 5;
y = y + 5;
setTimeout(drawCanvas, 200);
platypus.src = "http://www.wildwatch.com.au/uploads/Platypus/PLATYPUSweb1.jpg"
}
</script>
</head>
<body>
<h1>Hello Canvas.</h1>
<canvas id="myCanvas" width="500" height="300">Your browser does not support HTML5 canvas.</
</body>
</html>
I've been following various guides and have the base code up for a simple animation but for the life of me I cannot get the canvas to reset correctly. The clearRect() function is working perfectly but when I try to draw an arc again immediatly afterwards it draws the sum of all the paths again rather than just drawing the single segment of the circle.
Can someone tell me what I'm doing wrong here, I know it's a simple solution! In short I would like the test page below to produce a kind of spinning segment instead of just drawing a circle:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<span id="degrees_output" style="display:block;width:60px"></span>
<button onclick="continue_animation=false;">Stop</button>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var degrees = 0;
var continue_animation = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var output = document.getElementById('degrees_output');
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate() {
// update
output.innerHTML = degrees;
var radians = (degrees / 180) * Math.PI;
if (degrees >= 360)
degrees = 0;
else
degrees += 1;
// clear
if (degrees % 20 == 0)
{
context.clearRect(0, 0, 578, 200);
}
context.beginPath();
// setup the line style
context.strokeStyle = '#fa00ff';
context.lineWidth = 5;
context.lineCap = 'round';
context.arc(50, 50, 20, 0, radians, false);
// colour the path
context.stroke();
context.closePath();
// request new frame
requestAnimFrame(function() {
if (continue_animation)
animate();
});
}
animate();
</script>
If you want a fixed length arc to sweep around your circle, you'll want to specify both the starting and ending angles in your context.arc like this:
context.arc(50, 50, 20, startRadians, radians, false);
and startRadians can just be any angle behind your "radians" value:
var startRadians= (degrees-45) * Math.PI/180;
and, Yes, you will need to clear the canvas (at least the previous arc) before drawing the arc in a new position:
context.clearRect(0,0,canvas.width,canvas.height);
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/VFhzX/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var degrees = 0;
var continue_animation = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var output = document.getElementById('degrees_output');
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate() {
// update
output.innerHTML = degrees;
var radians = (degrees / 180) * Math.PI;
var startRadians= (degrees-45) * Math.PI/180;
if (degrees >= 360)
degrees = 0;
else
degrees += 1;
// clear
if (degrees % 20 == 0)
{
context.clearRect(0, 0, 578, 200);
}
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
// setup the line style
context.strokeStyle = '#fa00ff';
context.lineWidth = 5;
context.lineCap = 'round';
context.arc(50, 50, 20, startRadians, radians, false);
// colour the path
context.stroke();
context.closePath();
// request new frame
requestAnimFrame(function() {
if (continue_animation)
animate();
});
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<span id="degrees_output" style="display:block;width:60px"></span>
<button onclick="continue_animation=false;">Stop</button>
<canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>
On a button click I call a script to get the canvas Image. I take the location. I need to pass this image source into another jsp file where I need to display this image.
Can you please help me out in this.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<script>
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.beginPath();
var x;
var y;
canvas.onmousedown = function(e) {
x = e.clientX;
y = e.clientY;
ctx.moveTo(x, y);
}
canvas.onmouseup = function(e) {
x = null;
y = null;
}
canvas.onmousemove = function(e) {
if (x == null || y == null) {
return;
}
x = e.clientX;
y = e.clientY;
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
ctx.moveTo(x, y);
}
};
function to_image(){
var canvas = document.getElementById("canvas");
document.getElementById("theimage").src = canvas.toDataURL();
}
function clear_image(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillStyle = '#ffffff';
context.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="300" height="300"
style="border: 1px solid black;"></canvas>
<div><button onclick="to_image()">Draw to Image</button></div>
<div><button onclick="clear_image()">Clear</button></div>
<image id="theimage"></image>
</body>
</html>
I need to pass the value of document.getElementById("theimage").src into another jsp and access that value to dispaly the image.
Can anybody help me out in this.
If you meant you will load that second page with image on a button click from the first page(for which you have pasted code)then just update the code as:
{
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL();
//-- Following code can be placed wherever you want to call another page.
window.location = "urlToSecondJSPPage.jsp?imgUrl="+dataUrl;
}
And then imgUrl(url parameter) can be accessed from second page.