0

I want to link an image from CSS to Javascript but my code does not work.

CSS :

.backImage {

    background-image: url("img/level1.jpg");
    background-repeat: repeat-y;

}

Javascript Code :

var x1 = 450;
var y1 = 40;
var speed1 = 5;
var angle1 = 90;
var mod1 = 1;        

var tmp= $("<div>").addClass('backImage');
var src = tmp.css('background-image').match(/[^"][^"]+/g)[1];

console.log(src);

var back = new Image();
    back.src = src;  

function drawBackground() {

    x1 += (speed1 * mod1) * Math.cos(Math.PI / 180 * angle1);
    y1 += (speed1 * mod1) * Math.sin(Math.PI / 180 * angle1);

    context.save();
    context.translate(x1, y1);
    context.rotate(Math.PI / 180 * angle1);
    context.drawImage(back, -(back.width / 2), -(back.height / 2));
    context.restore();

} 
3
  • What do you mean by "link?" Have you tried moving the context.drawImage(...) call into an image onload handler? Why do you need to do this at all? It seems like an XY problem. Commented Dec 13, 2014 at 1:54
  • You mean this(code just updated) Commented Dec 13, 2014 at 1:57
  • "but my code does not work" - what doesn't work specifically? you can't get the filename? you can't assign it to back.src? what? Commented Dec 13, 2014 at 2:03

1 Answer 1

1

I'm guessing you want to extract an image from the CSS background-image source and draw it on canvas. This is how its done.

var tmp = $("<div>").addClass('backImage');
var src = tmp.css('background-image').match(/[^"][^"]+/g)[1];
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');

console.log(src);

var back = new Image();
back.src = src;
back.onload = drawBackground;

function drawBackground() {
  canvas.width = back.width;
  canvas.height = back.height;
  context.drawImage(back, 0, 0);
}
.backImage {
  background-image: url("http://placehold.it/200/200");
  background-repeat: repeat-y;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>

Sign up to request clarification or add additional context in comments.

9 Comments

The background is not showing up, heres a fiddle i made: jsfiddle.net/jesse_meth/xp8echja
But on the fiddle i already have javascript, i dont have to use that.
@TheGoodGuy - I don't understand. What are you expecting to it to load as background?
just to get that onto the canvas but load it on javascript
Yah but theres no image on the canvas
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.