Wrapping a text around an image in a Canvas - html

Is it possible to wrap a text around an image inside an HTML 5 Canvas? For example using some Javascript framework? I looked into KineticJS, but couldn't find something useful.
Edit:
It seems my question is unclear. I'm looking for something lke this :
http://www.monkeydoit.com/images/panda2.gif

You can wrap text around an image (rectangle) using canvas transforms (translate+rotate)
For example, this is how you rotate the canvas and draw text down the right side of your image:
// save the untransformed state of the context
ctx.save();
// translate to the top-right corner of the image
// ( x/y properties have been added to the standard img element )
ctx.translate(image.x+image.width,image.y);
// rotate the canvas 90 degrees (PI/2 radians)
ctx.rotate(Math.PI/2);
// the canvas is now properly moved and rotated
// so we can just draw the text at [0,0]
ctx.fillText(subtext,0,0);
// restore the context to its untransformed state
ctx.restore();
This calculates how many words fit on a side using context.measureText:
var end=0;
var subtext="";
while(ctx.measureText(text.split(" ",end+1).join(" ")).width<=length)
{
subtext=text.split(" ",end+1).join(" ");
end++;
}
An interesting enhancement would be to draw text around a rectangle with rounded corners.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/U2hE3/
<!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; padding:10px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var rect={x:40,y:40,width:150,height:120};
var text="This is some text that wraps on the outside of a rectangle.";
var font="14px Verdana";
drawTextAroundRect(rect,text,7,font);
function drawTextAtAngle(text,length,x,y,radians){
// if text is empty then return
if(text.length==0){return;}
var end=0;
var subtext="";
if(ctx.measureText(text).width<=length){
// all the text fits
subtext=text;
}else{
// calc how many words will fit on this length
while(ctx.measureText(text.split(" ",end+1).join(" ")).width<=length)
{
subtext=text.split(" ",end+1).join(" ");
end++;
}
}
// draw the text at the appropriate angle
ctx.save();
ctx.translate(x,y);
ctx.rotate(radians);
ctx.fillText(subtext,0,0);
ctx.restore();
// return any text that didn't fit for further processing
if(end==text.length){
return("");
}else{
return(text.substr(subtext.length));
}
}
function drawTextAroundRect(rect,text,textPadding,font){
// set the font
ctx.font=font;
// top
text=drawTextAtAngle(text,rect.width,rect.x,rect.y-textPadding,0);
// right
text=drawTextAtAngle(text,rect.height,rect.x+rect.width+textPadding,rect.y,Math.PI/2);
// bottom
text=drawTextAtAngle(text,rect.width,rect.x+rect.width,rect.y+rect.height+textPadding,Math.PI);
// left
text=drawTextAtAngle(text,rect.height,rect.x-textPadding,rect.y+rect.height,Math.PI*1.5);
// draw the rect (just for illustration)
ctx.beginPath();
ctx.rect(rect.x,rect.y,rect.width,rect.height);
ctx.stroke();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=250></canvas>
</body>
</html>
[ Add more word-wrap code given questioners clarification ]
You can use context.measureText to get the width of text and use that to wrap text around an image.
Given text width you can build a word-wrap by advancing to the next line when text exceeds your desired width.
In the case of wrapping around a picture, you will have 2 desired widths—shorter while the text might run into the image and longer after that.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/XM5Yp/
<!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 canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var maxWidth = 350;
var lineHeight = 25;
var x = (canvas.width - maxWidth) / 2;
var y = 60;
var text = "'Twas the night before Christmas, when all through the house. Not a creature was stirring, not even a mouse. The stockings were hung by the chimney with care in hopes that St. Nicholas soon would be there.";
ctx.font = '16pt Calibri';
ctx.fillStyle = '#333';
var imgWidth;
var imgHeight;
var img=new Image();
img.onload=function(){
imgWidth=img.width;
imgHeight=img.height;
ctx.drawImage(img,canvas.width-img.width,0)
wrapText(text, x, y, maxWidth, lineHeight);
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg";
function wrapText(text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
var maxLineWidth=y>imgHeight+10?maxWidth:maxWidth-imgWidth;
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if(testWidth > maxLineWidth) {
ctx.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
maxLineWidth= y>imgHeight+10?maxWidth:maxWidth-imgWidth;
}
else {
line = testLine;
}
}
ctx.fillText(line, x, y);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=400 height=325></canvas>
</body>
</html>

Related

Cannot cut multiple shapes from canvas

I am trying to cut certain pattern from file based canvas and i need multiple geometrical shapes used.
For that, i am drawing shapes on that canvas using globalCompositeOperation set to XOR.
$( document ).ready(function() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'http://cimsec.org/wp-content/uploads/2014/01/adriatic-sea-horizon-igor-voljc.jpg';
var width = img.naturalWidth/2; // this will be 300
var height = img.naturalHeight/2; // this will be 400
document.getElementById('canvas').width = width;
document.getElementById('canvas').height = height;
img.onload = function() {
ctx.drawImage(img, 0,0, width, height);
}
ctx.globalCompositeOperation = "xor";
function circle(x, y, radius)
{
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.fill();
}
var iks = width/2;
var sr = width/5;
var igrek = (sr);
circle(iks,igrek,sr);
var igrek2 = 3.5*sr;
circle(iks,igrek2,sr);
});
.lw { font-size: 60px; }
body {background-color:blue}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->
<canvas id="canvas"></canvas>
<!-- End your code here -->
</body>
</html>
Unfortunetly, it does not work correctly if i try cut more than one shape. On example on litewave only second shape is cut correctly, first one only has its perimeter cut.
Ultimately i plan to have ths shape cut from image, white area on this jpg example shoudl be transparent:
http://www.detroitbodyproducts.com/media/wysiwyg/hide.jpg
Is there any better way to do this?
You need to call ctx.beginPath(); first, or else it doesn't work:
$( document ).ready(function() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'http://cimsec.org/wp-content/uploads/2014/01/adriatic-sea-horizon-igor-voljc.jpg';
var width = img.naturalWidth/2; // this will be 300
var height = img.naturalHeight/2; // this will be 400
document.getElementById('canvas').width = width;
document.getElementById('canvas').height = height;
img.onload = function() {
ctx.drawImage(img, 0,0, width, height);
}
ctx.globalCompositeOperation = "xor";
function circle(x, y, radius)
{
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.fill();
}
var iks = width/2;
var sr = width/5;
var igrek = (sr);
circle(iks,igrek,sr);
var igrek2 = 3.5*sr;
circle(iks,igrek2,sr);
});
.lw { font-size: 60px; }
body {background-color:blue}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->
<canvas id="canvas"></canvas>
<!-- End your code here -->
</body>
</html>

HTML5 Canvas image flashes and script does not wait for image to be downloaded

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>

Canvas draw shapes on the go

When I run it the browser loads for a while and then displays the whole canvas. How can I make it display as soon as it finishes one loop iteration?And why is this code not doing what I expect it to?
This is my code:
for(var i=0;i<50;i++){
for(var j=0;j<50;j++){
ctx.beginPath();
ctx.fillRect(10*j, 10*i, 10, 10);
ctx.fillStyle = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
ctx.fill();
ctx.closePath();
sleep(10);
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
OK... I managed to achieve the desired effect using
window.requestAnimationFrame(draw);
However can someone please explain why the code above behaves the way it does? Why does it draw all 2500 shapes before it displays the canvas?
Use requestAnimationFrame
Here's code and a Fiddle: http://jsfiddle.net/m1erickson/NRBy5/
<!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 canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var RAF;
var i=0;
var j=0;
function animate() {
// draw stuff
ctx.beginPath();
ctx.fillRect(10*j, 10*i, 10, 10);
ctx.fillStyle = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
ctx.fill();
ctx.closePath();
// update
j+=1;
console.log(i+"/"+j);
if(j>=50){
i+=1;
j=0;
if(i>=50){
cancelAnimationFrame(RAF);
}
}
// request new frame
RAF=requestAnimationFrame(function() { animate(); });
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Create links in HTML canvas

Is it possible to create html links out of text that is rendered in a canvas element?
There is no easy way. You will have to draw the link text onto the canvas and then check for mouseclicks. Here is a demo html page:
<html>
<head>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx;
var linkText="https://stackoverflow.com";
var linkX=5;
var linkY=15;
var linkHeight=10;
var linkWidth;
var inLink = false;
// draw the balls on the canvas
function draw(){
canvas = document.getElementById("myCanvas");
// check if supported
if(canvas.getContext){
ctx=canvas.getContext("2d");
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw the link
ctx.font='10px sans-serif';
ctx.fillStyle = "#0000ff";
ctx.fillText(linkText,linkX,linkY);
linkWidth=ctx.measureText(linkText).width;
//add mouse listeners
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
}
}
//check if the mouse is over the link and change cursor style
function on_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { //for firefox
x = ev.layerX;
y = ev.layerY;
}
x-=canvas.offsetLeft;
y-=canvas.offsetTop;
//is the mouse over the link?
if(x>=linkX && x <= (linkX + linkWidth) && y<=linkY && y>= (linkY-linkHeight)){
document.body.style.cursor = "pointer";
inLink=true;
}
else{
document.body.style.cursor = "";
inLink=false;
}
}
//if the link has been clicked, go to link
function on_click(e) {
if (inLink) {
window.location = linkText;
}
}
</script>
</head>
<body onload="draw()">
<center>
<canvas id="myCanvas" width="200" height="200" style="border-style:solid;border-width:1px">Canvas not supported.</canvas>
</center>
</body>
</html>
This example shows how you can add multiple links to your HTML canvas:
<!DOCTYPE html>
<!-- This page shows how to add multiple links to <canvas> (by Yakovenko Max) -->
<html>
<head>
<title>Canvas Links Example</title>
<script>
function OnLoad(){
// Get canvas
var canvas = document.getElementById("myCanvas");
// 2d context
var ctx = canvas.getContext("2d");
ctx.translate(0.5, 0.5); // * Move the canvas by 0.5px to fix blurring
// Block border
ctx.strokeStyle = "#5F7FA2";
ctx.strokeRect(50, 50, 185, 90);
// Photo
var img = new Image();
img.src = "http://www.cs.washington.edu/education/courses/csep576/05wi/projects/project4/web/artifact/liebling/average_face.gif";
img.onload = function(){
ctx.drawImage(img, 59.5, 59.5); // Use -0.5px on photos to prevent blurring caused by * fix
}
// Text
ctx.fillStyle = "#000000";
ctx.font = "15px Tahoma";
ctx.textBaseline = "top";
ctx.fillText("Username", 95, 65);
// ***** Magic starts here *****
// Links
var Links = new Array(); // Links information
var hoverLink = ""; // Href of the link which cursor points at
ctx.fillStyle = "#0000ff"; // Default blue link color
ctx.font = "15px Courier New"; // Monospace font for links
ctx.textBaseline = "top"; // Makes left top point a start point for rendering text
// Draw the link
function drawLink(x,y,href,title){
var linkTitle = title,
linkX = x,
linkY = y,
linkWidth = ctx.measureText(linkTitle).width,
linkHeight = parseInt(ctx.font); // Get lineheight out of fontsize
// Draw the link
ctx.fillText(linkTitle, linkX, linkY);
// Underline the link (you can delete this block)
ctx.beginPath();
ctx.moveTo(linkX, linkY + linkHeight);
ctx.lineTo(linkX + linkWidth, linkY + linkHeight);
ctx.lineWidth = 1;
ctx.strokeStyle = "#0000ff";
ctx.stroke();
// Add mouse listeners
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
// Add link params to array
Links.push(x + ";" + y + ";" + linkWidth + ";" + linkHeight + ";" + href);
}
// Link hover
function on_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element
if (ev.layerX || ev.layerX == 0) { // For Firefox
x = ev.layerX;
y = ev.layerY;
}
// Link hover
for (var i = Links.length - 1; i >= 0; i--) {
var params = new Array();
// Get link params back from array
params = Links[i].split(";");
var linkX = parseInt(params[0]),
linkY = parseInt(params[1]),
linkWidth = parseInt(params[2]),
linkHeight = parseInt(params[3]),
linkHref = params[4];
// Check if cursor is in the link area
if (x >= linkX && x <= (linkX + linkWidth) && y >= linkY && y <= (linkY + linkHeight)){
document.body.style.cursor = "pointer";
hoverLink = linkHref;
break;
}
else {
document.body.style.cursor = "";
hoverLink = "";
}
};
}
// Link click
function on_click(e) {
if (hoverLink){
window.open(hoverLink); // Use this to open in new tab
//window.location = hoverLink; // Use this to open in current window
}
}
// Ready for use ! You are welcome !
drawLink(95,93,"http://www.facebook.com/","Me at facebook");
drawLink(95,110,"http://plus.google.com/","Me at G+");
}
</script>
</head>
<body onload="OnLoad();">
<canvas id="myCanvas" width="450" height="250" style="border:1px solid #eee;">
Canvas is not supported in your browser ! :(
</canvas>
</body>
</html>
There is nothing built in to do it, but you can emulate the function of links if you wanted to. You can remember where the text is, color it differently, give it a different cursor when the user mouses-over that area, and redirect the user to another page when he or she clicks on it.
I think another easy idea is to put a div at the position where you want the link to appear on the canvas and put your link at the div. All you will have to do is to position and style the div correctly.
"I think another easy idea is to put a div at the position where you want the link to appear on the canvas and put your link at the div. All you will have to do is to position and style the div correctly." -Shamaila Tahir
I personally like the idea of using links on top of the canvas and here is a full page sized canvas example. You could use this example for many things, and not just the canvas, so why not get comfortable with it. `
<!DOCTYPE html>
<HEAD>
<style type="text/css">
html { height: 100%; width: 100%; overflow: hidden; }
body {
position: absolute;
height: 100%;
width: 100%;
overflow:hidden;
}
#contactBackground{
position: absolute;
height:100%;
width: 100%;
border: 2px solid green;
}
#contactBackground:hover{
border: 2px solid red;}
#contact{
position: absolute;
height:15%;
top: 52%;
left:70%;
width: 10%;
background-size:20%,20%;
}
#onOff{
position: absolute;
height:15%;
top: 52%;
left:20%;
width: 10%;
background-size:20%,20%;
}
#onOff:hover{border: 2px solid red;}
</style><TITLE>Kewl!! Buttons and Links with Canvas</TITLE></HEAD>
<script type="text/javascript">
window.addEventListener('load', canvas, false);
function canvas(){
var link="contact";
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
contact = document.getElementById("contact");
onOff = document.getElementById("onOff");
document.getElementById("onOff").style.visibility="visible";
switchLinks(link);
function switchLinks(isLink){
if(isLink!="contact"){
document.getElementById("contact").style.visibility="hidden";
}
if(isLink=="contact"){
document.getElementById("contact").style.visibility="visible";
}
}
onOff.addEventListener("mousedown",contactFunction, false);
function contactFunction(){
if(link=="contact"){link="";}else{link="contact";}
switchLinks(link);
}
}
</script><body>
<canvas id="canvas" width="0" height="0">Your browser does not support the HTML 5 Canvas.
</canvas>
<span id="contact" style="display:hidden">
<img id="contactBackground" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQP5qi1TPhjAPOfbogNgppFdc4r1LoNmr5D1n-NBfr7ll3x9VlY9w" alt="Send a message" title="Email" />
</span>
<img id="onOff" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXvh9Fej5ZhBQstjlSpQbRLx46h47KS2IO_WIfoyyrHk_essLU" style="display:hidden" />
</body></HTML>``
A simpler solution can be implemented by using a mousedown event listener. First create two arrays for the x and y coordinates of your links on the canvas. Then test if a click was within a range of a link on a mouseup. It it was, use a window.open('http://myurl.com') method to open the link.
var links = ['Google','Yahoo','Bing','Baidu','DuckDuckGo'];
var coordx = [425,332,251,306,458];
var coordy = [267,402,335,304,438];
myCanvas.mousedown(function(e){
lastEvent = e;
mouseDown = true;
}).mouseup(function(){
if((lastEvent.offsetX) > (coordx[0] - 5) &&
(lastEvent.offsetX) <= (coordx[0] + 5) &&
(lastEvent.offsetY) > (coordy[0] - 5) &&
(lastEvent.offsetY) < (coordy[0] + 5)){
// use a console.log('x = "+lastEvent.offsetX) first to find the coordinates and ranges for the links.
// link to 1st url in myArray
window.open('http://myFirstURL.com');
} `
});
You will need tests for each set of coordinates, or you can specify a variable for a current active link.
This is my first stackoverflow post. Thanks to all you guys who have helped me over the years.

HTML Canvas; Given two Xs and two Ys, Center Text within

I am making a series of rectangles. This is not the entire script, this code will actually be within a function with parameters for x and y coordinates and parameters for height and width. This function will be used to create multiple rectangles. My question is that I need to center the text within rectangles of x,y,width and height ... and the text will vary in length.
<!DOCTYPE html>
<html lang="en">
<body>
<canvas id="myCanvas" width="400" height="350">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var x = 10;
var y = 10;
var width = 180;
var height = 75;
var c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.lineWidth = 5;
ctx.strokeStyle="black";
ctx.strokeRect(x,y,width,height);
ctx.textBaseline = 'top';
ctx.font = '20px Sans-Serif';
ctx.fillStyle = 'blue';
ctx.fillText ("hello", 30, 50);
</script>
</body>
</html>
You can use the measureText method of your context to calculate the position of your text before drawing it.
to center vertically use this:
context.textBaseline = "middle";
y_pos = text_area_height / 2;
Use the textAlign property:
context.textAlign = 'center';
http://www.html5canvastutorials.com/tutorials/html5-canvas-text-align/