简体   繁体   中英

Add content on an image with canvas

My client wants to show an emission label on his e-commerce site. The label looks like this:

在此处输入图片说明

And there is 448 possible variants of this with the arrows pointing to different values.

I was wondering if it would be better to only have a base image of this (without the arrows), and then add add content on it.

How would I do this using canvas? I know how to draw a line using canvas, but that's about it. Should I use a 3rd party library for this? I'm already using jQuery but that's not going to get me anywhere.

So, tl;dr;

Place 3 "arrows" on image, and fill them with text. How do I align the arrows correctly?

You could accomplish your task in many ways.

Here's an example using your html canvas suggestion of an image drawn on canvas without arrows and then using canvases drawing commands to apply the arrows:

http://jsfiddle.net/m1erickson/u8TCv/

在此处输入图片说明

Example code:

<!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 img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/emission.png";
    function start(){
        canvas.width=img.width;
        canvas.height=img.height;
        ctx.drawImage(img,0,0);
        drawArrow(91,166,56,36,15,"C");
    }

    function drawArrow(x,y,w,h,pointWidth,text){
        // arrow
        ctx.beginPath();
        ctx.moveTo(x,y);
        ctx.lineTo(x+pointWidth,y-h/2);
        ctx.lineTo(x+w,y-h/2);
        ctx.lineTo(x+w,y+h/2);
        ctx.lineTo(x+pointWidth,y+h/2);
        ctx.closePath();
        ctx.fillStyle="black";
        ctx.fill();
        // text
        ctx.font="36px arial black";
        ctx.fillStyle="white";
        ctx.fillText(text,x+pointWidth+5,y+h/3);
    }

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM