Example of using Canvas in HTML5 (adding mouse clicks and dragging interactions to images)

Source: Internet
Author: User
Tags pow prepare

Canvas is an unreserved drawing interface that does not record the previous execution of the drawing operation, but rather maintains the final result (the color pixels that make up the image).
If you want to make canvas interactive, such as the user can select, drag graphics on the canvas. Then we have to record every object we draw in order to modify and redraw them in the future, and to interact.

1, mouse click to select Graphics objects
(1) Click the "Add Circle" button in the example below to add a random circle of position, size, and color to the canvas.
(2) Click the "Empty Canvas" button to clear all the circles on the canvas.
(3) The mouse clicks any circle, the circle will appear the black border, indicates the selection.
Add Circle Empty Canvas

Code Description:
(1) In order to be able to save the Circle object, we define a function class called Circle () to create a custom object. At the same time, to allow this object to hold the data, use the keyword this to create the attribute.
(2) the Drawcircles () function is used to populate the canvas with the collection of the current circle. Each time the program refreshes the canvas, the Clearrect () method is used to clear all the content on the canvas. But don't be careful. This can cause the canvas to blink, the circle on the canvas disappears all at once and then appears again.
Because canvas is optimized for this problem, all the drawing logic is finished before it clears or plots everything to ensure the final result is smooth.
(3) To achieve a mouse to select an image, it is necessary to use collision detection. That is to calculate whether the point that the mouse clicks falls in a shape. For a circle, just calculate the line distance between the click and Center.

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>hangge.com</title>

<style>
Canvas {
Cursor:pointer;
BORDER:1PX solid black;
}
</style>
<script>
This method is used to store each circle object
function Circle (x, y, radius, color) {
this.x = x;
This.y = y;
This.radius = radius;
This.color = color;
this.isselected = false;
}

Save all the circles on the canvas
var circles = [];

var canvas;
var context;

Window.onload = function () {
Canvas = document.getElementById ("Canvas");
Context = Canvas.getcontext ("2d");

Canvas.onmousedown = Canvasclick;
};

function Addrandomcircle () {
Computes a random size and position for the circle
var radius = Randomfromto (10, 60);
var x = randomfromto (0, Canvas.width);
var y = randomfromto (0, canvas.height);

Calculate a random color for a circle
var colors = ["Green", "Blue", "red", "yellow", "magenta", "orange", "Brown", "Purple", "pink"];
var color = colors[randomfromto (0, 8)];

Create a new Circle
var circle = new Circle (x, y, radius, color);

Save it in an array
Circles.push (circle);

Redraw Canvas
Drawcircles ();
}

function Clearcanvas () {
Remove all Circles
circles = [];

Redraw the canvas.
Drawcircles ();
}

function Drawcircles () {
Clear the canvas and prepare to draw
Context.clearrect (0, 0, canvas.width, canvas.height);

Traverse all Circles
for (var i=0; i<circles.length; i++) {
var circle = circles[i];

Draw a Circle
Context.globalalpha = 0.85;
Context.beginpath ();
Context.arc (circle.x, Circle.y, Circle.radius, 0, math.pi*2);
Context.fillstyle = Circle.color;
Context.strokestyle = "BLACK";

if (circle.isselected) {
Context.linewidth = 5;
}
else {
Context.linewidth = 1;
}
Context.fill ();
Context.stroke ();
}
}

var previousselectedcircle;

function Canvasclick (e) {
Get the clicked Point on the canvas
var Clickx = E.pagex-canvas.offsetleft;
var clicky = e.pagey-canvas.offsettop;

Find a clicked Circle
for (var i=circles.length-1; i>=0; i--) {
var circle = circles[i];
Use the Pythagorean theorem to calculate the distance between this point and the center of the circle
var distancefromcenter = math.sqrt (Math.pow (Circle.x-clickx, 2)
+ Math.pow (Circle.y-clicky, 2))
To determine if this point is in the circle.
if (Distancefromcenter <= Circle.radius) {
Clear the previously selected circle
if (previousselectedcircle!= null) previousselectedcircle.isselected = FALSE;
Previousselectedcircle = circle;

Select New Circle
Circle.isselected = true;

Update display
Drawcircles ();

Stop Search
Return
}
}
}

Generate random numbers within a range
function Randomfromto (from, to) {
Return Math.floor (Math.random () * (To-from + 1) + from);
}
</script>

<body>

<canvas id= "Canvas" width= "height=" >
</canvas>

<div>
<button onclick= "addrandomcircle ()" > Add Circle </button>
<button onclick= "Clearcanvas ()" > Clear canvas </button>
</div>

</body>

2, drag the mouse drawing object

Here's a feature improvement that allows the user to drag a circle over the canvas. As long as you listen for canvas onMouseMove events, modify the coordinates of the circle accordingly, and then call the Drawcircle () function to redraw the canvas.
Add Circle Empty Canvas
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>hangge.com</title>

<style>
Canvas {
Cursor:pointer;
BORDER:1PX solid black;
}
</style>
<script>
This method is used to store each circle object
function Circle (x, y, radius, color) {
this.x = x;
This.y = y;
This.radius = radius;
This.color = color;
this.isselected = false;
}

Save all the circles on the canvas
var circles = [];

var canvas;
var context;

Window.onload = function () {
Canvas = document.getElementById ("Canvas");
Context = Canvas.getcontext ("2d");

Canvas.onmousedown = Canvasclick;
Canvas.onmouseup = stopdragging;
Canvas.onmouseout = stopdragging;
Canvas.onmousemove = dragcircle;
};

function Addrandomcircle () {
Computes a random size and position for the circle
var radius = Randomfromto (10, 60);
var x = randomfromto (0, Canvas.width);
var y = randomfromto (0, canvas.height);

Calculate a random color for a circle
var colors = ["Green", "Blue", "red", "yellow", "magenta", "orange", "Brown", "Purple", "pink"];
var color = colors[randomfromto (0, 8)];

Create a new Circle
var circle = new Circle (x, y, radius, color);

Save it in an array
Circles.push (circle);

Redraw Canvas
Drawcircles ();
}

function Clearcanvas () {
Remove all Circles
circles = [];

Redraw the canvas.
Drawcircles ();
}

function Drawcircles () {
Clear the canvas and prepare to draw
Context.clearrect (0, 0, canvas.width, canvas.height);

Traverse all Circles
for (var i=0; i<circles.length; i++) {
var circle = circles[i];

Draw a Circle
Context.globalalpha = 0.85;
Context.beginpath ();
Context.arc (circle.x, Circle.y, Circle.radius, 0, math.pi*2);
Context.fillstyle = Circle.color;
Context.strokestyle = "BLACK";

if (circle.isselected) {
Context.linewidth = 5;
}
else {
Context.linewidth = 1;
}
Context.fill ();
Context.stroke ();
}
}

var previousselectedcircle;

function Canvasclick (e) {
Get the clicked Point on the canvas
var Clickx = E.pagex-canvas.offsetleft;
var clicky = e.pagey-canvas.offsettop;

Find a clicked Circle
for (var i=circles.length-1; i>=0; i--) {
var circle = circles[i];
Use the Pythagorean theorem to calculate the distance between this point and the center of the circle
var distancefromcenter = math.sqrt (Math.pow (Circle.x-clickx, 2)
+ Math.pow (Circle.y-clicky, 2))
To determine if this point is in the circle.
if (Distancefromcenter <= Circle.radius) {
Clear the previously selected circle
if (previousselectedcircle!= null) previousselectedcircle.isselected = FALSE;
Previousselectedcircle = circle;

Select New Circle
Circle.isselected = true;

Allow the circle to drag
Isdragging = true;

Update display
Drawcircles ();

Stop Search
Return
}
}
}

Generate random numbers within a range
function Randomfromto (from, to) {
Return Math.floor (Math.random () * (To-from + 1) + from);
}

var isdragging = false;

function stopdragging () {
Isdragging = false;
}

function Dragcircle (e) {
Determine if the circle starts dragging
if (isdragging = = True) {
To determine whether a drag object exists
if (previousselectedcircle!= null) {
Get mouse position
var x = E.pagex-canvas.offsetleft;
var y = e.pagey-canvas.offsettop;

Move the circle to the mouse position
previousselectedcircle.x = x;
Previousselectedcircle.y = y;

Update Canvas
Drawcircles ();
}
}
}
</script>

<body>

<canvas id= "Canvas" width= "height=" >
</canvas>

<div>
<button onclick= "addrandomcircle ()" > Add Circle </button>
<button onclick= "Clearcanvas ()" > Clear canvas </button>
</div>

</body>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.