¿Es posible crear enlaces html fuera del texto que se representa en un elemento canvas?Crear enlaces en lienzo HTML
Respuesta
No hay una manera fácil. Deberá dibujar el texto del enlace en el lienzo y luego verificar si hay clics del mouse. Aquí es una página de prueba HTML:
<html>
<head>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx;
var linkText="http://stackoverflow.com";
var linkX=5;
var linkY=15;
var linkHeight=10;
var linkWidth;
var inLink = false;
// draw the balls on the canvas
function draw(){
canvas = document.getElementById("myCanvas");
// check if supported
if(canvas.getContext){
ctx=canvas.getContext("2d");
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw the link
ctx.font='10px sans-serif';
ctx.fillStyle = "#0000ff";
ctx.fillText(linkText,linkX,linkY);
linkWidth=ctx.measureText(linkText).width;
//add mouse listeners
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
}
}
//check if the mouse is over the link and change cursor style
function on_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { //for firefox
x = ev.layerX;
y = ev.layerY;
}
x-=canvas.offsetLeft;
y-=canvas.offsetTop;
//is the mouse over the link?
if(x>=linkX && x <= (linkX + linkWidth) && y<=linkY && y>= (linkY-linkHeight)){
document.body.style.cursor = "pointer";
inLink=true;
}
else{
document.body.style.cursor = "";
inLink=false;
}
}
//if the link has been clicked, go to link
function on_click(e) {
if (inLink) {
window.location = linkText;
}
}
</script>
</head>
<body onload="draw()">
<center>
<canvas id="myCanvas" width="200" height="200" style="border-style:solid;border-width:1px">Canvas not supported.</canvas>
</center>
</body>
</html>
No hay nada incorporado en para hacerlo, pero puede emular la función de los enlaces si lo desea. Puede recordar dónde está el texto, colorearlo de manera diferente, darle un cursor diferente cuando el usuario pasa el ratón por esa área y redirigir al usuario a otra página cuando hace clic en él.
creo que otra idea fácil es poner un div en la posición en la que desea que aparezca el vínculo en el lienzo y poner su enlace en la div. Todo lo que tendrá que hacer es posicionar y darle estilo al div correctamente.
Este ejemplo muestra cómo se pueden agregar múltiples enlaces a tus lienzo HTML:
<!DOCTYPE html>
<!-- This page shows how to add multiple links to <canvas> (by Yakovenko Max) -->
<html>
<head>
<title>Canvas Links Example</title>
<script>
function OnLoad(){
// Get canvas
var canvas = document.getElementById("myCanvas");
// 2d context
var ctx = canvas.getContext("2d");
ctx.translate(0.5, 0.5); // * Move the canvas by 0.5px to fix blurring
// Block border
ctx.strokeStyle = "#5F7FA2";
ctx.strokeRect(50, 50, 185, 90);
// Photo
var img = new Image();
img.src = "http://www.cs.washington.edu/education/courses/csep576/05wi/projects/project4/web/artifact/liebling/average_face.gif";
img.onload = function(){
ctx.drawImage(img, 59.5, 59.5); // Use -0.5px on photos to prevent blurring caused by * fix
}
// Text
ctx.fillStyle = "#000000";
ctx.font = "15px Tahoma";
ctx.textBaseline = "top";
ctx.fillText("Username", 95, 65);
// ***** Magic starts here *****
// Links
var Links = new Array(); // Links information
var hoverLink = ""; // Href of the link which cursor points at
ctx.fillStyle = "#0000ff"; // Default blue link color
ctx.font = "15px Courier New"; // Monospace font for links
ctx.textBaseline = "top"; // Makes left top point a start point for rendering text
// Draw the link
function drawLink(x,y,href,title){
var linkTitle = title,
linkX = x,
linkY = y,
linkWidth = ctx.measureText(linkTitle).width,
linkHeight = parseInt(ctx.font); // Get lineheight out of fontsize
// Draw the link
ctx.fillText(linkTitle, linkX, linkY);
// Underline the link (you can delete this block)
ctx.beginPath();
ctx.moveTo(linkX, linkY + linkHeight);
ctx.lineTo(linkX + linkWidth, linkY + linkHeight);
ctx.lineWidth = 1;
ctx.strokeStyle = "#0000ff";
ctx.stroke();
// Add mouse listeners
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
// Add link params to array
Links.push(x + ";" + y + ";" + linkWidth + ";" + linkHeight + ";" + href);
}
// Link hover
function on_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element
if (ev.layerX || ev.layerX == 0) { // For Firefox
x = ev.layerX;
y = ev.layerY;
}
// Link hover
for (var i = Links.length - 1; i >= 0; i--) {
var params = new Array();
// Get link params back from array
params = Links[i].split(";");
var linkX = parseInt(params[0]),
linkY = parseInt(params[1]),
linkWidth = parseInt(params[2]),
linkHeight = parseInt(params[3]),
linkHref = params[4];
// Check if cursor is in the link area
if (x >= linkX && x <= (linkX + linkWidth) && y >= linkY && y <= (linkY + linkHeight)){
document.body.style.cursor = "pointer";
hoverLink = linkHref;
break;
}
else {
document.body.style.cursor = "";
hoverLink = "";
}
};
}
// Link click
function on_click(e) {
if (hoverLink){
window.open(hoverLink); // Use this to open in new tab
//window.location = hoverLink; // Use this to open in current window
}
}
// Ready for use ! You are welcome !
drawLink(95,93,"http://www.facebook.com/","Me at facebook");
drawLink(95,110,"http://plus.google.com/","Me at G+");
}
</script>
</head>
<body onload="OnLoad();">
<canvas id="myCanvas" width="450" height="250" style="border:1px solid #eee;">
Canvas is not supported in your browser ! :(
</canvas>
</body>
</html>
¿Por qué no usar un hash en lugar de pasar una cadena delimitada por ";"? – scottmrogowski
Usaría JSON en lugar de una cadena delimitada, p. Ej. links.push ({"x": x, "y": y, "ancho": linkWidth, "altura": linkHeight, "href": href}); Además, la adición de detectores de eventos se puede hacer fuera de drawLink, ya que solo deben agregarse una vez. –
"Creo que otra idea fácil es poner un div en la posición en la que desea que aparezca el vínculo en el lienzo y poner su enlace en el div. Todo lo que tendrá que hacer es colocar y darle estilo al div correctamente ". -Shamaila Tahir
Personalmente me gusta la idea de usar enlaces en la parte superior del lienzo y aquí hay un ejemplo de lienzo de tamaño completo. Puede usar este ejemplo para muchas cosas, y no solo para el lienzo, entonces, ¿por qué no sentirse cómodo con él? `
<!DOCTYPE html>
<HEAD>
<style type="text/css">
html { height: 100%; width: 100%; overflow: hidden; }
body {
position: absolute;
height: 100%;
width: 100%;
overflow:hidden;
}
#contactBackground{
position: absolute;
height:100%;
width: 100%;
border: 2px solid green;
}
#contactBackground:hover{
border: 2px solid red;}
#contact{
position: absolute;
height:15%;
top: 52%;
left:70%;
width: 10%;
background-size:20%,20%;
}
#onOff{
position: absolute;
height:15%;
top: 52%;
left:20%;
width: 10%;
background-size:20%,20%;
}
#onOff:hover{border: 2px solid red;}
</style><TITLE>Kewl!! Buttons and Links with Canvas</TITLE></HEAD>
<script type="text/javascript">
window.addEventListener('load', canvas, false);
function canvas(){
var link="contact";
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
contact = document.getElementById("contact");
onOff = document.getElementById("onOff");
document.getElementById("onOff").style.visibility="visible";
switchLinks(link);
function switchLinks(isLink){
if(isLink!="contact"){
document.getElementById("contact").style.visibility="hidden";
}
if(isLink=="contact"){
document.getElementById("contact").style.visibility="visible";
}
}
onOff.addEventListener("mousedown",contactFunction, false);
function contactFunction(){
if(link=="contact"){link="";}else{link="contact";}
switchLinks(link);
}
}
</script><body>
<canvas id="canvas" width="0" height="0">Your browser does not support the HTML 5 Canvas.
</canvas>
<span id="contact" style="display:hidden">
<a href="mailto:Dude your Awesome!"><img id="contactBackground" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQP5qi1TPhjAPOfbogNgppFdc4r1LoNmr5D1n-NBfr7ll3x9VlY9w" alt="Send a message" title="Email" /></a>
</span>
<img id="onOff" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXvh9Fej5ZhBQstjlSpQbRLx46h47KS2IO_WIfoyyrHk_essLU" style="display:hidden" />
</body></HTML>``
- 1. Cómo centrar enlaces en HTML
- 2. Android crear capas en lienzo
- 3. Enlaces HTML y usabilidad
- 4. HTML5 Crear dinámicamente lienzo
- 5. lienzo html: recorte y texto
- 6. html lienzo texto desbordamiento elipsis
- 7. Lienzo HTML - Dibujar flechas curvas
- 8. Lienzo HTML como superposición en Google Maps
- 9. html - enlaces sin protocolo http
- 10. Interfaz de usuario con zoom en el lienzo HTML
- 11. Construir un calibre circular html 5 lienzo
- 12. Lienzo HTML: trazo punteado alrededor del círculo
- 13. Cómo evitar la auto-estiramiento lienzo HTML
- 14. obtener clics a través del lienzo html
- 15. HTML Treebuilder XPath para extraer enlaces
- 16. ¿Es posible crear un lienzo transparente
- 17. crear la barra de menús HTML en HTML
- 18. Dibuje un polígono que se interseca en el lienzo HTML
- 19. Cómo dibujar un rectángulo redondeado en el lienzo HTML?
- 20. ¿Puede tener múltiples regiones de recorte en un lienzo HTML?
- 21. Uso del relleno par impar en el lienzo HTML
- 22. ¿Cómo escalar un imageData en el lienzo HTML?
- 23. Photoshop en línea a través del lienzo de HTML 5?
- 24. ¿Cómo giro un único objeto en un lienzo html 5?
- 25. Dibujando una espiral en un lienzo HTML usando JavaScript
- 26. ¿Crear clickboxes 'no rectangulares' para enlaces?
- 27. Forma preferida de crear enlaces con backbone.js
- 28. Lienzo HTML como superposición en Google Maps que se repara en relación con el lienzo del mapa
- 29. Cómo cambiar el tamaño del elemento de lienzo html?
- 30. Generar datos de imagen del elemento de lienzo HTML
¿Cuál es esta línea para' if (ev.layerX || ev.layerX) '. Simplemente no puedo resolverlo. ¿No es 'if (x || x)' lo mismo que 'if (x)'? – xbonez
@xbonez debe ser 'ev.layerX || ev.layerX == 0'. Lo he corregido – dogbane