I need this code fixed. I need the .png image im using to work when you mouseove
ID: 662971 • Letter: I
Question
I need this code fixed. I need the .png image im using to work when you mouseover so he moves on the canvas with your mouse. Also need to add "transforms" to the composition. PLEASE HELP ASAP
<!DOCTYPE html>
<html lang="en">
<head>
<title>Drawing Loop</title>
<script type="text/javascript"> src="stickguy.png"
var ctx;
var img;
var x = 0;
var y = 40;
function setup() {
var canvas = document.getElementById('lessonCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
img = new Image();
img.onload = function(){
setInterval(function () { draw(); }, 36);
}
img.src = 'stickguy.png';
}
}
function draw() {
drawBackground();
<!--stickguy-->
ctx.drawImage(img, x, y);
x += 3;
if(x > 300){
x = -50;
y=Math.random()*300;
}
}
function drawBackground(){
<!-- green field -->
var lineGrad = ctx.createLinearGradient(150, 0, 150, 300);
lineGrad.addColorStop(0, 'black');
lineGrad.addColorStop(1, '#008000');
ctx.fillStyle = lineGrad;
ctx.fillRect(0, 0, 300, 300);
$(document).mousemove(function(e) {
$('stickguy.png').offset({
left: e.pageX,
top: e.pageY + 20
});
});
}
</script>
</head>
<body>
<canvas id="lessonCanvas" width="300" height="300"style="margin:100px;"></canvas>
</body>
</html>
Explanation / Answer
Calling drawBackground function caused error make sure it is placed in the correct place.
I removed calling drawBackground function it worked
<!DOCTYPE html>
<html lang="en">
<head>
<title>Drawing Loop</title>
<script type="text/javascript"> src="stickguy.png"
var ctx;
var img;
var x = 0;
var y = 40;
function setup() {
var canvas = document.getElementById('lessonCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
img = new Image();
img.onload = function(){
setInterval(function () { draw(); }, 36);
}
img.src = 'stickguy.png';
}
}
function draw() {
<!--stickguy-->
ctx.drawImage(img, x, y);
x += 3;
if(x > 300){
x = -50;
y=Math.random()*300;
}
}
function drawBackground(){
<!-- green field -->
var lineGrad = ctx.createLinearGradient(150, 0, 150, 300);
lineGrad.addColorStop(0, 'black');
lineGrad.addColorStop(1, '#008000');
ctx.fillStyle = lineGrad;
ctx.fillRect(0, 0, 300, 300);
$(document).mousemove(function(e) {
$('stickguy.png').offset({
left: e.pageX,
top: e.pageY + 20
});
});
}
</script>
</head>
<body>
<canvas id="lessonCanvas" width="300" height="300"style="margin:100px;"></canvas>
</body>
</html>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.