Related
I am working on a fun intro project to HTML Canvas. The basic concept is that some shapes in this case circles move around and bounce off the sides. The two problems I would like help with are:
After resizing the browser the circles may get stuck at the end of the screen on the open sides(bottom and right) where they are bounded by widthCanvas and heightCanvas. Ideally, I would the circles to behave the same way as they do on the sides(left and top) where they are bounded by 0. (See the if statements in the animate() function)
How to remove the white space around the canvas left due to the use of:
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,
body {
overflow: hidden;
}
</style>
</head>
<body onresize="resizeCanvas()">
<div>
<canvas id="canvas"></canvas>
</div>
<script>
const canvas = document.getElementById('canvas');
/** #type {CanvasRenderingContext2D} */
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
widthCanvas = canvas.width;
heightCanvas = canvas.height;
draw(40);
function draw(num) {
//number of cycles
num_cycles = num;
// speed bounds
min_speed = 4;
// real max_speed is + min_speed
max_speed = 3;
// create arrays for changing values
const arr_x = new Array(num_cycles);
const arr_y = new Array(num_cycles);
const arr_dx = new Array(num_cycles);
const arr_dy = new Array(num_cycles);
const arr_r = new Array(num_cycles);
// populate arrays with random vaalues in range so circles
// have different velocities on y and x as well as vary in radii
for (let index = 0; index < num_cycles; index++) {
arr_x[index] = ((widthCanvas * 0.2) * Math.random()) + (widthCanvas * 0.4);
arr_y[index] = ((heightCanvas * 0.2) * Math.random()) + (heightCanvas * 0.4);
arr_dx[index] = (min_speed + Math.random() * max_speed) * (Math.round(Math.random()) ? -1 : 1);
arr_dy[index] = (min_speed + Math.random() * max_speed) * (Math.round(Math.random()) ? 1 : -1);
arr_r[index] = 50 + Math.random() * widthCanvas / 12;
}
let arr_color = ["rgba(47, 133, 209, 0.6)", "rgba(244, 67, 54, 0.6)", "rgba(71, 50, 123, 0.6)", "rgba(241, 194, 50, 0.6)", "rgba(56, 118, 29, 0.6)"];
function animate() {
//clear the canvas so that new drawings are on a blank canvas
ctx.clearRect(0, 0, widthCanvas, heightCanvas)
ctx.fillStyle = "rgba(224, 31, 92, 1)";
ctx.fillRect(0, 0, widthCanvas, heightCanvas)
// Draw shapes aand animations
for (var i = 0; i <= widthCanvas; i += widthCanvas / 120) {
addLinesPath(i, i, 0, heightCanvas, "rgba(31, 118, 224, 0.5)");
}
for (let index = 0; index < num_cycles; index++) {
draw_circle(arr_x[index], arr_y[index], arr_r[index], arr_color[index % arr_color.length])
if (arr_x[index] + arr_r[index] > widthCanvas || arr_x[index] - arr_r[index] < 0)
arr_dx[index] = -arr_dx[index];
if (arr_y[index] + arr_r[index] > heightCanvas || arr_y[index] - arr_r[index] < 0)
arr_dy[index] = -arr_dy[index];
arr_x[index] += arr_dx[index];
arr_y[index] += arr_dy[index];
}
requestAnimationFrame(animate);
}
animate()
}
// resize
function resizeCanvas() {
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
widthCanvas = canvas.width;
heightCanvas = canvas.height;
}
function get_width() {
return canvas.width;
}
function get_height() {
return canvas.height;
}
// draw line
function addLinesPath(y_start, y_end, x_start, x_end, color) {
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(y_start, x_start);
ctx.lineTo(y_end, x_end);
ctx.stroke();
}
// draw circle
function draw_circle(x, y, r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.fill();
}
</script>
</body>
</html>
After resizing the browser the circles may get stuck...
Consider following simplified code from your snippet:
if (arr_x[index] + arr_r[index] > widthCanvas)
arr_dx[index] = -arr_dx[index];
Here, when the circle goes out of right border due to resizing, the if statement evaluates to true all the time. Because you are switching direction every frame! 😬
Make sure you switch the direction only once after the circle goes out of the canvas.
How to remove the white space around the canvas left...
By default <body> has some margin. In Chrome 8px. Need to check other browser. Get rid of those margins and paddings if any on all the involved elements. Or adjust the canvas width in code accordingly.
Demo:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,
body {
overflow: hidden;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body onresize="resizeCanvas()">
<div>
<canvas id="canvas"></canvas>
</div>
<script>
const canvas = document.getElementById('canvas');
/** #type {CanvasRenderingContext2D} */
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
widthCanvas = canvas.width;
heightCanvas = canvas.height;
draw(10);
function draw(num) {
//number of cycles
num_cycles = num;
// speed bounds
min_speed = 2;
// real max_speed is + min_speed
max_speed = 2;
// create arrays for changing values
const arr_x = new Array(num_cycles);
const arr_y = new Array(num_cycles);
const arr_dx = new Array(num_cycles);
const arr_dy = new Array(num_cycles);
const arr_r = new Array(num_cycles);
// populate arrays with random vaalues in range so circles
// have different velocities on y and x as well as vary in radii
for (let index = 0; index < num_cycles; index++) {
arr_x[index] = ((widthCanvas * 0.2) * Math.random()) + (widthCanvas * 0.4);
arr_y[index] = ((heightCanvas * 0.2) * Math.random()) + (heightCanvas * 0.4);
arr_dx[index] = (min_speed + Math.random() * max_speed) * (Math.round(Math.random()) ? -1 : 1);
arr_dy[index] = (min_speed + Math.random() * max_speed) * (Math.round(Math.random()) ? 1 : -1);
arr_r[index] = 50 + Math.random() * widthCanvas / 12;
}
let arr_color = ["rgba(47, 133, 209, 0.6)", "rgba(244, 67, 54, 0.6)", "rgba(71, 50, 123, 0.6)", "rgba(241, 194, 50, 0.6)", "rgba(56, 118, 29, 0.6)"];
function animate() {
//clear the canvas so that new drawings are on a blank canvas
ctx.clearRect(0, 0, widthCanvas, heightCanvas)
ctx.fillStyle = "rgba(224, 31, 92, 1)";
ctx.fillRect(0, 0, widthCanvas, heightCanvas)
// Draw shapes and animations
for (var i = 0; i <= widthCanvas; i += widthCanvas / 120) {
addLinesPath(i, i, 0, heightCanvas, "rgba(31, 118, 224, 0.5)");
}
for (let index = 0; index < num_cycles; index++) {
draw_circle(arr_x[index], arr_y[index], arr_r[index], arr_color[index % arr_color.length])
if (arr_x[index] + arr_r[index] > widthCanvas && arr_dx[index] > 0)
arr_dx[index] *= -1;
else if (arr_x[index] - arr_r[index] < 0 && arr_dx[index] < 0)
arr_dx[index] *= -1;
if (arr_y[index] + arr_r[index] > heightCanvas && arr_dy[index] > 0)
arr_dy[index] *= -1;
else if (arr_y[index] - arr_r[index] < 0 && arr_dy[index] < 0)
arr_dy[index] *= -1;
arr_x[index] += arr_dx[index];
arr_y[index] += arr_dy[index];
}
requestAnimationFrame(animate);
}
animate()
}
// resize
function resizeCanvas() {
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
widthCanvas = canvas.width;
heightCanvas = canvas.height;
console.log(widthCanvas, '=', heightCanvas);
}
function get_width() {
return canvas.width;
}
function get_height() {
return canvas.height;
}
// draw line
function addLinesPath(y_start, y_end, x_start, x_end, color) {
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(y_start, x_start);
ctx.lineTo(y_end, x_end);
ctx.stroke();
}
// draw circle
function draw_circle(x, y, r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.fill();
}
</script>
</body>
</html>
Here, to avoid complex code I've separated the if statements.
With simple debugging we can easily figure out such pesky bugs. This guide may help: https://developer.chrome.com/docs/devtools/javascript/
I am trying to set this HTML code to a Chromebook background. Is this possible? I also don't want to have to use any extensions.
<style>*{
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html, body{
height: 100%;
margin: 0;
padding: 0;
background-color: #333;
overflow: hidden;
}
canvas{
background-color: #000;
}</style>
<div class="container">
<div class="row">
<canvas id="nokey" width="800" height="800">
</canvas>
</div>
</div>
<script>
var canvas = document.getElementById('nokey'),
can_w = parseInt(canvas.getAttribute('width')),
can_h = parseInt(canvas.getAttribute('height')),
ctx = canvas.getContext('2d');
// console.log(typeof can_w);
var ball = {
x: 0,
y: 0,
vx: 0,
vy: 0,
r: 0,
alpha: 1,
phase: 0
},
ball_color = {
r: 207,
g: 255,
b: 4
},
R = 2,
balls = [],
alpha_f = 0.03,
alpha_phase = 0,
// Line
link_line_width = 0.8,
dis_limit = 260,
add_mouse_point = true,
mouse_in = false,
mouse_ball = {
x: 0,
y: 0,
vx: 0,
vy: 0,
r: 0,
type: 'mouse'
};
// Random speed
function getRandomSpeed(pos){
var min = -1,
max = 1;
switch(pos){
case 'top':
return [randomNumFrom(min, max), randomNumFrom(0.1, max)];
break;
case 'right':
return [randomNumFrom(min, -0.1), randomNumFrom(min, max)];
break;
case 'bottom':
return [randomNumFrom(min, max), randomNumFrom(min, -0.1)];
break;
case 'left':
return [randomNumFrom(0.1, max), randomNumFrom(min, max)];
break;
default:
return;
break;
}
}
function randomArrayItem(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function randomNumFrom(min, max){
return Math.random()*(max - min) + min;
}
console.log(randomNumFrom(0, 10));
// Random Ball
function getRandomBall(){
var pos = randomArrayItem(['top', 'right', 'bottom', 'left']);
switch(pos){
case 'top':
return {
x: randomSidePos(can_w),
y: -R,
vx: getRandomSpeed('top')[0],
vy: getRandomSpeed('top')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'right':
return {
x: can_w + R,
y: randomSidePos(can_h),
vx: getRandomSpeed('right')[0],
vy: getRandomSpeed('right')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'bottom':
return {
x: randomSidePos(can_w),
y: can_h + R,
vx: getRandomSpeed('bottom')[0],
vy: getRandomSpeed('bottom')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'left':
return {
x: -R,
y: randomSidePos(can_h),
vx: getRandomSpeed('left')[0],
vy: getRandomSpeed('left')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
}
}
function randomSidePos(length){
return Math.ceil(Math.random() * length);
}
// Draw Ball
function renderBalls(){
Array.prototype.forEach.call(balls, function(b){
if(!b.hasOwnProperty('type')){
ctx.fillStyle = 'rgba('+ball_color.r+','+ball_color.g+','+ball_color.b+','+b.alpha+')';
ctx.beginPath();
ctx.arc(b.x, b.y, R, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
});
}
// Update balls
function updateBalls(){
var new_balls = [];
Array.prototype.forEach.call(balls, function(b){
b.x += b.vx;
b.y += b.vy;
if(b.x > -(50) && b.x < (can_w+50) && b.y > -(50) && b.y < (can_h+50)){
new_balls.push(b);
}
// alpha change
b.phase += alpha_f;
b.alpha = Math.abs(Math.cos(b.phase));
// console.log(b.alpha);
});
balls = new_balls.slice(0);
}
// loop alpha
function loopAlphaInf(){
}
// Draw lines
function renderLines(){
var fraction, alpha;
for (var i = 0; i < balls.length; i++) {
for (var j = i + 1; j < balls.length; j++) {
fraction = getDisOf(balls[i], balls[j]) / dis_limit;
if(fraction < 1){
alpha = (1 - fraction).toString();
ctx.strokeStyle = 'rgba(150,150,150,'+alpha+')';
ctx.lineWidth = link_line_width;
ctx.beginPath();
ctx.moveTo(balls[i].x, balls[i].y);
ctx.lineTo(balls[j].x, balls[j].y);
ctx.stroke();
ctx.closePath();
}
}
}
}
// calculate distance between two points
function getDisOf(b1, b2){
var delta_x = Math.abs(b1.x - b2.x),
delta_y = Math.abs(b1.y - b2.y);
return Math.sqrt(delta_x*delta_x + delta_y*delta_y);
}
// add balls if there a little balls
function addBallIfy(){
if(balls.length < 20){
balls.push(getRandomBall());
}
}
// Render
function render(){
ctx.clearRect(0, 0, can_w, can_h);
renderBalls();
renderLines();
updateBalls();
addBallIfy();
window.requestAnimationFrame(render);
}
// Init Balls
function initBalls(num){
for(var i = 1; i <= num; i++){
balls.push({
x: randomSidePos(can_w),
y: randomSidePos(can_h),
vx: getRandomSpeed('top')[0],
vy: getRandomSpeed('top')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
});
}
}
// Init Canvas
function initCanvas(){
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
can_w = parseInt(canvas.getAttribute('width'));
can_h = parseInt(canvas.getAttribute('height'));
}
window.addEventListener('resize', function(e){
console.log('Window Resize...');
initCanvas();
});
function goMovie(){
initCanvas();
initBalls(20);
window.requestAnimationFrame(render);
}
goMovie();
// Mouse effect
canvas.addEventListener('mouseenter', function(){
console.log('mouseenter');
mouse_in = true;
balls.push(mouse_ball);
});
canvas.addEventListener('mouseleave', function(){
console.log('mouseleave');
mouse_in = false;
var new_balls = [];
Array.prototype.forEach.call(balls, function(b){
if(!b.hasOwnProperty('type')){
new_balls.push(b);
}
});
balls = new_balls.slice(0);
});
canvas.addEventListener('mousemove', function(e){
var e = e || window.event;
mouse_ball.x = e.pageX;
mouse_ball.y = e.pageY;
// console.log(mouse_ball);
});
</script>
Since you said, "Chromebook." There's no native support for it as you're asking; without extension.
According to Google's Chromebook Help, they state only .png & .jpg backgrounds.
If you haven't yet, download an image (.png or .jpg) from the web that
you’d like as your wallpaper.
Also, referencing the crosexperts website, it states:
there’s no native support for moving wallpapers, we had to create an
engine — and editor — to make this possible. But, amazingly, it is
possible.
Chrome OS doesn’t support Live Wallpapers in any way.
So im working on a tile game for school and not very familiar with programming so apologies if the answer is obvious.
Using an array ive created a map with different tiles- what i want is so that when the character walks across a certain array then something happens - eg: restart the game
My code is all in one .as file :
package {
import flash.display.MovieClip;
import flash.events.*;
public class main2 extends MovieClip {
public function main2() {
// Create map
var mapWidth = 10;
var mapHeight = 10;
var tileSide = 32;
var totalTiles = mapWidth * mapHeight;
var myMap: Array = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 2, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 3, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];
for (var i: int = 0; i < mapHeight; i++) {
for (var u: int = 0; u < mapWidth; u++) {
var cell: MovieClip = new tile();
cell.gotoAndStop(myMap[i][u] + 1);
cell.x = tileSide * u
cell.y = tileSide * i
addChild(cell);
}
}
// Hero management
var heroSpawnX = 1
var heroSpawnY = 1
var character: hero = new hero();
addChild(character)
character.x = heroSpawnX * tileSide
character.y = heroSpawnY * tileSide
var heroX = heroSpawnX
var heroY = heroSpawnY
// Basic movement
stage.addEventListener(KeyboardEvent.KEY_DOWN, movement);
function movement(event: KeyboardEvent): void {
if (event.keyCode == 40 && myMap[heroY + 1][heroX] != 1) {
character.gfx.rotation = 0
character.y += tileSide
heroY++ //Down
}
if (event.keyCode == 38 && myMap[heroY - 1][heroX] != 1) {
character.gfx.rotation = 180
character.y -= tileSide
heroY-- //Up
}
if (event.keyCode == 39 && myMap[heroY][heroX + 1] != 1) {
character.gfx.rotation = 270
character.x += tileSide
heroX++ //Right
}
if (event.keyCode == 37 && myMap[heroY][heroX - 1] != 1) {
character.gfx.rotation = 90
character.x -= tileSide
heroX-- //Left
}
} //movement function
} // behind this line
}
}
In my array there is a '2' in the second row. I want my character to walk across that tile and 'die'- but more just restart from his spawn postion ([1][1]). I assume an event listener would be needed but after googleing some codes- still can not get it to work.
Thanks in advance for any help
add these pieces to your code:
this function returns the number of the specified tile:
function getNumberAt(tileX:uint,tileY:uint){
var value:uint=myMap[tileX][tyleY];
return value
}
note that your indices for this function should start from zero( if you want tile at first horizontal and second vertical,you should getNumberAt(0,1)
now replace your function:
function movement(event: KeyboardEvent): void {
if (event.keyCode == 40 && myMap[heroY + 1][heroX] != 1) {
character.gfx.rotation = 0
character.y += tileSide
heroY++ //Down
}
if (event.keyCode == 38 && myMap[heroY - 1][heroX] != 1) {
character.gfx.rotation = 180
character.y -= tileSide
heroY-- //Up
}
if (event.keyCode == 39 && myMap[heroY][heroX + 1] != 1) {
character.gfx.rotation = 270
character.x += tileSide
heroX++ //Right
}
if (event.keyCode == 37 && myMap[heroY][heroX - 1] != 1) {
character.gfx.rotation = 90
character.x -= tileSide
heroX-- //Left
}
trace(getNumberAt(heroX,heroY))//test getNumberAt function
if(getNumberAt(heroX,heroY)==2){
//type your code for death here
}
}
I  h☻p e this helps !
very new to as3 and using a tutorial found here to try my hand at tile based movement. However, i cant seem to get the code to work. I keep getting the error code:
"1046: Type was not found or was not a compile-time constant:hero."
The line it is reference is:
var character: hero = new hero();
My full code is:
package {
import flash.display.MovieClip;
import flash.events.*;
public class main2 extends MovieClip {
var hero;
public function main2() {
// Create map
var mapWidth = 10;
var mapHeight = 10;
var tileSide = 32;
var totalTiles = mapWidth * mapHeight;
var myMap: Array = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];
for (var i: int = 0; i < mapHeight; i++) {
for (var u: int = 0; u < mapWidth; u++) {
var cell: MovieClip = new tile();
cell.gotoAndStop(myMap[i][u] + 1);
cell.x = tileSide * u;
cell.y = tileSide * i;
addChild(cell);
}
}
// Hero management
var heroSpawnX = 4;
var heroSpawnY = 2;
var character: hero = new hero();
addChild(character);
character.x = heroSpawnX * tileSide;
character.y = heroSpawnY * tileSide;
var heroX = heroSpawnX;
var heroY = heroSpawnY;
// Basic movement
stage.addEventListener(KeyboardEvent.KEY_DOWN, movement);
function movement(event: KeyboardEvent):void {
if (event.keyCode == 40 && myMap[heroY + 1][heroX] == 0) {
character.gfx.rotation = 0;
character.y += tileSide;
heroY++;
}
if (event.keyCode == 38 && myMap[heroY - 1][heroX] == 0) {
character.gfx.rotation = 180;
character.y -= tileSide;
heroY--;
}
if (event.keyCode == 39 && myMap[heroY][heroX + 1] == 0) {
character.gfx.rotation = 270;
character.x += tileSide;
heroX++;
}
if (event.keyCode == 37 && myMap[heroY][heroX - 1] == 0) {
character.gfx.rotation = 90;
character.x -= tileSide;
heroX--;
}
}
}
}
}
Any help on this issue would be great, been at it for an hour now.
also if you have any recommendations on as3 resources please let me know...specifically tiled based systems.
thanks is advanced.
That error means your class Hero is not found. you should put the hero.as file at where your main2.as file is(at same location as main2.as). and then import it:
import Hero;
Â
and my recommendation on as3 resources:
1.http://republicofcode.com:I think best site for starting as3.I started from it.
2.http://kirupa.com: a good site with a lot of articles
3.http://flashandmath.com: for professionals
and don't forget Adobe ActionScript-3 API reference:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/
I  H☺ P E   this helps !
I am trying to find how to filltext inside a rectangle. Unfortunately i can only find C# projects/tutorials.
Is it possible to add text inside a rectangle in HTML5 in a canvas?
I want each rectangle (node) to have a different text on it for example 1 is called cow and the other tiger and so on. Is this possible? i have tried everything!
var x = 150;
var y = 100;
var canvas = $('#NodeList').get(0);
var ctx = canvas.getContext('2d');
ctx.font = "30px Arial";
canvas.height = 0;
var rects = [
[20, 20, x, y],
[20, 220, x, y],
[20, 420, x, y],
[20, 620, x, y],
[20, 820, x, y],
[20, 1020, x, y],
[20, 1220, x, y],
[20, 1420, x, y],
[20, 1620, x, y]
];
for (var i = 0; i < rects.length; i++) {
canvas.height = canvas.height + 200;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//rectangles opnieuw tekenen
for (var j = 0; j < i; j++) {
ctx.fillRect(rects[j][0],
rects[j][1],
rects[j][2],
rects[j][3]);
}
ctx.fillRect(rects[i][0],
rects[i][1],
rects[i][2],
rects[i][3]);
}
$('#NodeList').click(function (e) {
var x = e.offsetX,
y = e.offsetY;
for (var i = 0; i < rects.length; i++) {
if (x > rects[i][0] && x < rects[i][0] + rects[i][2] && y > rects[i][1] && y < rects[i][1] + rects[i][3]) {
alert('Vierkant ' + i + ' clicked');
}
}
});
enter code here
I know its really old question. But I ran into a similar so I decided to post the answer.
Note: You have to treat canvas differently that html tags like div. You get one ctx for canvas and you paint on it like a stream. Just change the position of your next elements and it would as expected.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'red';
context.shadowColor = '#999';
context.shadowBlur = 20;
context.shadowOffsetX = 15;
context.shadowOffsetY = 15;
context.fill();
context.fillStyle = 'black';
context.font = '20px Courier';
context.shadowColor = 'transparent';
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.fillText(`List item`, 200, 80);
context.lineWidth = 7;
<canvas id="myCanvas" width="578" height="200"></canvas>