Javascript examples for Canvas:Example
Convert background-size and background-position relative values to absolute PX values
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> <style id="compiled-css" type="text/css"> #test {/* w w w .j a v a 2 s. c o m*/ width: 200px; height: 100px; background-repeat: no-repeat; background-size: 400px 267px; background-position: 20% 12%; /* Original position */ } </style> <script type="text/javascript"> $(function(){ var testDiv = $("#test"); var bgImgSize = testDiv.css("background-size").replace(/px|%/g, "").split(" "); var bgImgPosition = testDiv.css("background-position").replace(/px|%/g, "").split(" "); var bgImgXPosition = (bgImgPosition[0] == 100) ? (bgImgSize[0] - testDiv.width()) : ((bgImgSize[0] - testDiv.width()) * (bgImgPosition[0] * .01)); var bgImgYPosition = (bgImgPosition[1] == 100) ? (bgImgSize[1] - testDiv.height()) : ((bgImgSize[1] - testDiv.height()) * (bgImgPosition[1] * .01)); var props = { "divWidth": testDiv.width(), "divHeight": testDiv.height(), "bgImgWidth": bgImgSize[0], "bgImgHeight": bgImgSize[1], "bgImgXPosition": bgImgXPosition, "bgImgYPosition": bgImgYPosition, "bgImg": "https://www.java2s.com/style/demo/Google-Chrome.png" } var c = document.getElementById("test-canvas"); var ctx = c.getContext("2d"); var img = new Image(); img.onload = function() { ctx.drawImage(img, props.bgImgXPosition.toFixed(2), props.bgImgYPosition.toFixed(2), props.divWidth, props.divHeight, 0, 0, props.divWidth, props.divHeight); }; img.src = props.bgImg; }); </script> </head> <body> <div id="test"></div> <canvas id="test-canvas" width="200px" height="100"></canvas> </body> </html>